1

I have a problem with DI, it's new for me. I would like to give the Container as DI in my Project class, but i got an error :

Argument 1 passed to Project::__construct() must be an instance of Slim\Container, none given

I created a class Project :

use Slim\Container;

class Project {

    protected $ci;

    public function __construct(Container $ci) {
        $this->ci = $ci;
    }
}

Here my DIC configuration :

//dependencies.php
$container = $app->getContainer();

$container[Project::class] = function ($c) {
    return new Project($c);
};

And here my code index.php to run the code

    // Instantiate the app
    $settings = require __DIR__ . '/../app/configs/settings.php';

    $app = new \Slim\App($settings);

    // Set up dependencies
    require __DIR__ . '/../app/configs/dependencies.php';
    // Register middleware
    require __DIR__ . '/../app/configs/middleware.php';
    // Register routes
    require __DIR__ . '/../app/configs/routes.php';
    require __DIR__ . '/../app/model/Project.php';


    $app->get('/project/{id}', function (Request $request, Response $response) {
        $project = new Project();
        return $response;
    });
    $app->run();

I dont know where i failed, i even tried to use slim-brige, but i got the same result. I also tried to give a string instead of the the Container, and i still get null

Nirundthan
  • 13
  • 6

1 Answers1

0

Argument 1 passed to Project::__construct() must be an instance of Slim\Container, none given

Well, no argument given to the constructor indeed:

$app->get('/project/{id}', function (Request $request, Response $response) {
    $project = new Project(); // You should pass container instance here, but you don't
    return $response;
});

Since you have registered your Project class in the container, you can get instance from the container:

$app->get('/project/{id}', function (Request $request, Response $response) {
    $project = $this->container->get('Project'); // Get Project instance from the container, you have already registered it
    return $response;
});
Georgy Ivanov
  • 1,573
  • 1
  • 17
  • 24
  • Both are working. But i would like to call Project class without giving any parameters or calling the container. By using the DI, isnt supposed to be a implicite call ? – Nirundthan Oct 29 '16 at 09:30
  • "DIC" stands for "dependency injection container" and Slim uses Pimple by default: you register your objects in container, and pull them out when they're needed. [Smarter DIC can do it by themselves](http://stackoverflow.com/q/40176059/6850820). So the answer is: no, you can't instantiate `Project` class without passing arugments to its constructor - you need to pass arguments, either manually or using `$container`. – Georgy Ivanov Oct 29 '16 at 09:59
  • Thanks for this great answer – Nirundthan Oct 29 '16 at 11:30