1

I am using the Codebird Twitter SDK for PHP. The code requires you to set an OAuth token to a static variable before getting an instance of the class, e.g.

Codebird::setConsumerKey(a,b); //sets Codebird::_consumer_key and Codebird::_consumer_secret
$cb = Codebird::getInstance();

I run this in a class called TwitterApi which then passes the $cb instance around to a few other objects, firstly to a RequestFactory class, which then passes it to the various TwitterRequests created by the factory.

Everything works fine, apart from if I create the original TwitterApi class in the constructor of a Laravel Job, e.g:

public function __construct()
{
    $this->twitter = new TwitterApi();
}
public function handle()
{
    $this->twitter->doSomething();
}

In this case, the Codebird::_consumer_key and Codebird::_consumer_secret static variables are "lost" by the time the $cb instance reaches the TwitterRequest class. Weirdly, they are still set at the prior stage inside the RequestFactory, so they survive two passes but not the third.

Even more weirdly, the following code fixes the problem:

public function handle()
{
    $twitter = new TwitterApi();
    $twitter->doSomething();
}

The code also works fine in any other context other than when set as a property in the constructor of a Laravel job class. What is going on here? Why does the second code example work, but not the first?

I am assuming it is something to do with the job being serialized and put on the queue, but that doesn't explain why the static variables survive being passed from Class 1 => Class 2 but not Class 2 => Class 3.

lufc
  • 1,826
  • 2
  • 12
  • 18
  • Although it doesn't help you directly, I think [this is your answer](https://stackoverflow.com/a/1008094/231316). I don't know Laravel too well, but generally static fields aren't really expected to hold anything of consequence. Can you just move those two fields to environment/config variables and load them whenever you call the constructor? – Chris Haas May 19 '20 at 21:34
  • Maybe this is too obvious and dumb, but is "twitter" initialized in the class (outside of the constructor?). – Adam Winter May 19 '20 at 21:52
  • @AdamWinter, looking [through the source](https://github.com/jublo/codebird-php/blob/develop/src/codebird.php), that doesn't seem to be the issue, at least as far as I can tell. Maybe some other part is doing it elsewhere, however. – Chris Haas May 19 '20 at 22:01
  • That's the source for Codebird, not the rest of the class that contains the code you've shown in your question. I'm not so familiar with Laravel "Jobs" but $this refers to an object. Show me the rest of that object please. – Adam Winter May 19 '20 at 22:14
  • @ChrisHaas I checked and you're right that the static variables aren't serialized. (This is easily verifiable by running `serialize()` on the `$cb` object). This would explain why they are "lost" when they get put on the queue. – lufc May 20 '20 at 16:13

0 Answers0