1

I have a laravel app and have created a SocialMediaController to get the latest posts from twitter and instagram and store them in the database.

I need them to be universally accessible and know I can access it via the IOC.

public function doSomething(App\Http\Controllers\SocialMediaController 
    $SocialMedia) {

    }

However if feels wrong to inject a controller like this. What is be best way to wrap up these methods for global use?

LeBlaireau
  • 17,133
  • 33
  • 112
  • 192

1 Answers1

0

It seems like you want to share some logic you have in the SocialMediaController with another controller, right?

Instead of trying to pass a controller instance to the controller action using the service container, you may move the current logic to a service. Refer to Service Container and Service Providers in the Laravel docs on how to create your own services.

Another way to achieve that is using a trait. Check this answer on how you can do that https://stackoverflow.com/a/30365349/1128918. You would end up with something like this:

trait SocialFeeder {
    public function getLatestFromTwitter() {
        ...
    }
}

And, then, you can use that new trait with your controllers:

class SocialMediaController extends Controller {
    use SocialFeeder;
    public function doSomething() {
        ...
        $tweets = $this->getLatestFromTwitter();
        ...
    }
}
Gustavo Straube
  • 3,744
  • 6
  • 39
  • 62