I'm trying to inject a dependency into my Silex Controller, because I need an object of type user in my controller and handle some stuff with it.
$app->mount("/users", new \MyApp\Controller\Provider\User($user));
And I implemented the controller by implementing the ControllerProviderInterface:
class User implements ControllerProviderInterface{
protected $user;
public function __construct($user){
//...
}
public function connect(Application $app)
{
//...
}
}
The routes and the methods are all set up in the controller. Without the dependency injection everything works fine. But as long as I edit the code and add the injection I get the following error:
Missing argument 1 for ...::__construct()
When I create the object, I send that parameter to it, but somehow Silex creates an instance before with a constructor without passing any argument.
Another approach is to use a ServiceController instead of a ControllerProvider. You can achieve a more familiar dependency injection feel this way.
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app["user"] = function () {
return new User();
};
$app["user.controller"] = function () use ($app) {
return new UserController($app["user"]);
};
$app->get("/users/{id}", "user.controller:get");
...
class User implements UserInterface
{
// ...
}
...
class UserController
{
protected $user;
public function __construct(UserInterface $user)
{
$this->user = $user;
}
public function get(Request $request, $id)
{
$this->user;
// Do stuff
}
}
Reference: http://silex.sensiolabs.org/doc/providers/service_controller.html
Silex takes a different approach to dependency injection than you might be used to or might expect. Silex\Application is the dependency injection container that is available in almost any context in a Silex application. You register your dependencies with the $app and those dependencies are injected via the $app in any context you might need it. Here is an example of something you might do in your situation.
$app["user"] = function () {
return new \MyApp\Service\User();
};
$app->mount("/users", new \MyApp\Controller\Provider\User());
...
class User implements ControllerProviderInterface
{
public function connect(Application $app)
{
$controller = $app["controller_factory"];
$controller->get("/{id}", array($this, "get"));
return $controller;
}
public function get(Application $app, Request $request, $id)
{
$user = $app["user"];
// Do stuff
}
}
Dependency injection in Silex is different and it takes a little getting used to, but once you are comfortable with it, it's a pleasure to work with and it's very efficient.
This accepted answer is not the answer to the question. And the thing described in the answer is not dependency injection either, or a realy crude form of it. Its more like Hardcoding $app into your controllers.
The code in the question should work without changes. The code in the connect function and the constructor might be helpful to figure out, where your problem sits. Its not the call to mount, im sure.
Related
I am currently implementing repository pattern and dependency injection on my laravel project. But when I inject two or more class, I got this error
Too few arguments to function App\Repositories\UserRepository::__construct(), 0 passed
I don't know what's wrong but I think I did it correctly. Here's my code:
My service provider:
public function register()
{
$this->app->bind(LoanRepository::class, function() {
return new LoanRepository(new Loan, new UserRepository);
});
}
and here's my Repository
public function __construct($loan, $userRepository)
{
$this->loan = $loan;
$this->userRepository = $userRepository;
}
does anyone experience this?
The error is telling you that the UserRepository class is expecting some arguments that you are not passing it. Below would be an example of how you would pass a constructor argument to your new UserRepositiry call.
public function register()
{
$this->app->bind(LoanRepository::class, function() {
return new LoanRepository(new Loan, new UserRepository($constructorArgsHere);
});
}
I haven't worked with Laravel so I don't know what the UserRepository class constructor is looking for as arguments, but that should be an easy thing to find out just looking at the file where that class is defined or a quick google search.
We're trying to find the best way to implement dependency injection in a Symfony project with a quite specific problematic.
At user level, our application rely on an "Account" doctrine entity which is loaded with the help of the HTTP_HOST global against a domain property (multi-domain application). Going on the domain example.domain.tld will load the matching entity and settings.
At the devops level, we also need to do batch work with CLI scripts on many accounts at the same time.
The question we are facing is how to write services that will be compatible with both needs?
Let's illustrate this with a simplified example. For the user level we have this and everything works great:
Controller/FileController.php
public function new(Request $request, FileManager $fileManager): Response
{
...
$fileManager->addFile($file);
...
}
Service/FileManager.php
public function __construct(AccountFactory $account)
{
$this->account = $account;
}
Service/AccountFactory.php
public function __construct(RequestStack $requestStack, AccountRepository $accountRepository)
{
$this->requestStack = $requestStack;
$this->accountRepository = $accountRepository;
}
public function createAccount()
{
$httpHost = $this->requestStack->getCurrentRequest()->server->get('HTTP_HOST');
$account = $this->accountRepository->findOneBy(['domain' => $httpHost]);
if (!$account) {
throw $this->createNotFoundException(sprintf('No matching account for given host %s', $httpHost));
}
return $account;
}
Now if we wanted to write the following console command, it would fail because the FileManager is only accepting an AccountFactory and not the Account Entity.
$accounts = $accountRepository->findAll();
foreach ($accounts as $account) {
$fileManager = new FileManager($account);
$fileManager->addFile($file);
}
We could tweak in the AccountFactory but this would feel wrong...
In reality this is even worse because the Account dependency is deeper in services.
Does anyone have an idea how to make this properly ?
As a good practice, you should create an interface for the FileManager and set this FileManagerInterface as your dependency injection (instead of FileManager).
Then, you can have different classes that follow the same interface rules but just have a different constructor.
With this approach you can implement something like:
Service/FileManager.php
interface FileManagerInterface
{
// declare the methods that must be implemented
public function FileManagerFunctionA();
public function FileManagerFunctionB(ParamType $paramX):ReturnType;
}
FileManagerInterface.php
class FileManagerBase implements FileManagerInterface
{
// implement the methods defined on the interface
public function FileManagerFunctionA()
{
//... code
}
public function FileManagerFunctionB(ParamType $paramX):ReturnType
{
//... code
}
}
FileManagerForFactory.php
class FileManagerForFactory implements FileManagerInterface
{
// implement the specific constructor for this implementation
public function __construct(AccountFactory $account)
{
// your code here using the account factory object
}
// additional code that is needed for this implementation and that is not on the base class
}
FileManagerAnother.php
class FileManagerForFactory implements FileManagerInterface
{
// implement the specific constructor for this implementation
public function __construct(AccountInterface $account)
{
// your code here using the account object
}
// additional code that is needed for this implementation and that is not on the base class
}
Ans last but not least:
Controller/FileController.php
public function new(Request $request, FileManagerInterface $fileManager): Response
{
// ... code using the file manager interface
}
Another approach that also looks correct is, assuming that FileManager depends on an AccountInstance to work, changes could be made to your FileManager dependency to have the AccountInstance as a dependency instead of the Factory. Just Because in fact, the FileManager does not need the factory, it needs the result that the factory generates, so, automatically it is not FileManager's responsibility to carry the entire Factory.
With this approach you will only have to change your declarations like:
Service/FileManager.php
public function __construct(AccountInterface $account)
{
$this->account = $account;
}
Service/AccountFactory.php
public function createAccount():AccountInterface
{
// ... your code
}
In Laravel, I have a class that I would like to make available to the service controller, make some changes to in the controller action, and then render out with a ViewComposer.
I have done this several times before without issue, but for some reason this time my usual approach is not working - clearly I'm doing something different, and I'm beginning to suspect I've fundamentally misunderstood an aspect of what I am doing.
I have a ServiceProvider with this register() method:
public function register()
{
$this->app->singleton(HelperTest::class, function ($app) {
$pb = new HelperTest();
$pb->test = "jokes on you batman";
return $pb;
});
}
Then in my controller I'm doing the following:
private $helper;
public function __construct(HelperTest $pb)
{
$this->helper = $pb;
$this->helper->test = "hahah";
}
And then I have a viewcomposer doing the following:
private $helper;
public function __construct(HelperTest $pb)
{
$this->helper = $pb;
}
public function compose(View $view)
{
$view->with('output', $this->helper->test);
}
When I call {{ $output }} in the blade view, I expect to see hahah, but instead I get jokes on you batman.
My debugging has shown that all three of these methods are definitely being called. It looks to me like the ViewComposer is for some reason instantiating its own, fresh instance of the class. What am I doing wrong?
Thanks!
Execute php artisan optimize on your console, this will generate an optimized class loader for your application, then check if you can find your class HelperTest registered in services.php inside boostrap/cache. Until HelperTest is not registered there, Laravel IoC can't resolve your class.
Is it possible to inject a route-paramter (or an route segment) to the controller-constructor?
You find some code to clarify my question.
class TestController{
protected $_param;
public function __construct($paramFromRoute)
{
$this->param = $paramFromRoute;
}
public function testAction()
{
return "Hello ".$this->_param;
}
}
----------------------------------------------------
App::bind('TestController', function($app, $paramFromRoute){
$controller = new TestController($paramFromRoute);
return $controller;
});
----------------------------------------------------
// here should be some magic
Route::get('foo/{bar}', 'TestController');
It's not possible to inject them, but you have access to all of them via:
class TestController{
protected $_param;
public function __construct()
{
$id = Route::current()->getParameter('id');
}
}
Laravel 5.3.28
You can't inject the parameter...
But, you can inject the request and get it from the router instance, like this:
//route: url_to_controller/{param}
public function __construct(Request $request)
{
$this->param = $request->route()->parameter('param');
}
In Laravel 5.4, you can use this to request the parameter:
public function __construct(Request $request) {
$id = $request->get("id");
}
If you want a more testable solution, you can use Service Provider power.
$this->app->bind(TestController::class, function ($app) {
return new TestController(request()->testParam);
});
UPDATE FOR LARAVEL 8
you can use the route() method to get the value from the route url parameter from laravel 8:
$id = request()->route('id')
Lastly, but most importantly, you may simply "type-hint" the dependency in the constructor of a class that is resolved by the container, including controllers, event listeners, queue jobs, middleware, and more. In practice, this is how most of your objects are resolved by the container.
http://www.golaravel.com/laravel/docs/5.1/container/
I've been using Laravel for a while now and I have been reading a lot about Dependency Injection an testable code. I've come to a point of confusion when talking about Facades and Mocked Objects. I see two patterns:
class Post extends Eloquent {
protected $guarded = array();
public static $rules = array();
}
This is my Post Model. I could run Post::all(); to get all the posts from my blog. Now I want to incorporate it into my controller.
Option #1: Dependency Injection
My first instinct would be to inject the Post model as a dependecy:
class HomeController extends BaseController {
public function __construct(Post $post)
{
$this->post = $post;
}
public function index()
{
$posts = $this->posts->all();
return View::make( 'posts' , compact( $posts );
}
}
My unit test would look like this:
<?php
use \Mockery;
class HomeControllerTest extends TestCase {
public function tearDown()
{
Mockery::close();
parent::tearDown();
}
public function testIndex()
{
$post_collection = new StdClass();
$post = Mockery::mock('Eloquent', 'Post')
->shouldRecieve('all')
->once()
->andReturn($post_collection);
$this->app->instance('Post',$post);
$this->client->request('GET', 'posts');
$this->assertViewHas('posts');
}
}
Option #2: Facade Mocks
class HomeController extends BaseController {
public function index()
{
$posts = Post::all();
return View::make( 'posts' , compact( $posts );
}
}
My unit test would look like this:
<?php
use \Mockery;
class HomeControllerTest extends TestCase {
public function testIndex()
{
$post_collection = new StdClass();
Post::shouldRecieve('all')
->once()
->andReturn($post_collection);
$this->client->request('GET', 'posts');
$this->assertViewHas('posts');
}
}
I understand both methods but I don't understand why I should or when I should use one method over the other. For example, I've tried to use the DI route with the Auth class but it doesn't work so I have to use the Facade Mocks. Any calcification on this issue would be greatly appreciated.
Although you use dependency injection on Option #1, your controller is still coupled with the Eloquent ORM. (Note that i avoid to use the term Model here because in MVC the Model is not just a class or an object but a layer. It's your business logic.).
Dependency Injection allows for Dependency Inversion but they are not the same thing. According to the Dependency Inversion principle both high and low level code should depend on abstractions. In your case the high level code is your controller and the low level code is the Eloquent ORM that fetches data from MySQL, but as you can see none of them depends on abstractions.
As a consequence, you are not able to change your data access layer without affecting your controller. How would you go about changing for example from MySQL to MongoDB or to the File System? To do this you have to use repositories (or whatever you want to call it).
So create a repositories interface that all your concrete repository implementations (MySQL, MongoDB , File System etc.) should implement.
interface PostRepositoriesInterface {
public function getAll();
}
and then create your concrete implementation e.g. for MySQL
class DbPostRepository implements PostRepositoriesInterface {
public function getAll()
{
return Post::all()->toArray();
/* Why toArray()? This is the L (Liskov Substitution) in SOLID.
Any implementation of an abstraction (interface) should be substitutable
in any place that the abstraction is accepted. But if you just return
Post:all() how would you handle the situation where another concrete
implementation would return another data type? Probably you would use an if
statement in the controller to determine the data type but that's far from
ideal. In PHP you cannot force the return data type so this is something
that you have to keep in mind.*/
}
}
Now your controller must type hint the interface and not the concrete implementation. This is what "Code on an interface an not on implementation" is all about. This is Dependency Inversion.
class HomeController extends BaseController {
public function __construct(PostRepositoriesInterface $repo)
{
$this->repo= $repo;
}
public function index()
{
$posts = $this->repo->getAll();
return View::make( 'posts' , compact( $posts ) );
}
}
This way your controller is decoupled from your data layer. It's open for extension but closed for modification. You can switch to MongoDB or to the File System by creating a new concrete implementation of PostRepositoriesInterface (e.g. MongoPostRepository) and change only the binding from (Note that i don't use any namespaces here):
App:bind('PostRepositoriesInterface','DbPostRepository');
to
App:bind('PostRepositoriesInterface','MongoPostRepository');
In an ideal situation your controller should contain only application and not business logic. If you ever find yourself wanting to call a controller from another controller its a sign that you've done something wrong. In this case your controllers contain too much logic.
This also makes testing easier. Now you are able to test your controller without actually hitting the database. Note that a controller test must test only if the controller functions properly which means that the controller calls the right method, gets the results and pass it to the view. At this point you are not testing the validity of the results. This is not controller's responsibility.
public function testIndexActionBindsPostsFromRepository()
{
$repository = Mockery::mock('PostRepositoriesInterface');
$repository->shouldReceive('all')->once()->andReturn(array('foo'));
App::instance('PostRepositoriesInterface', $repository);
$response = $this->action('GET', 'HomeController#index');
$this->assertResponseOk();
$this->assertViewHas('posts', array('foo'));
}
EDIT
If you choose to go with option #1 you can test it like this
class HomeControllerTest extends TestCase {
public function __construct()
{
$this->mock = Mockery::mock('Eloquent', 'Post');
}
public function tearDown()
{
Mockery::close();
}
public function testIndex()
{
$this->mock
->shouldReceive('all')
->once()
->andReturn('foo');
$this->app->instance('Post', $this->mock);
$this->call('GET', 'posts');
$this->assertViewHas('posts');
}
}