I tried to get slim with PHP-DI and Autowiring working, without success. Maybe I have a wrong understanding of autowiring.
I setup a new project and created the following Index.php
:
require __DIR__ . '/../vendor/autoload.php';
use userservice\core\services\UserServiceInterface;
use userservice\infrastructure\services\UserService;
use userservice\webservice\controller\UsersController;
use DI\Container;
$app = \DI\Bridge\Slim\Bridge::create();
$container = $app->getContainer();
$container->set(UserServiceInterface::class, UserService::class);
$container->set(UsersController::class, UsersController::class);
$app->get('/user', [UsersController::class, 'get']);
$app->run();
The UsersController
namespace userservice\webservice\controller;
use userservice\core\services\UserServiceInterface;
class UsersController{
/**
*
* @var UserServiceInterface
*/
private $userService;
public function __construct(UserServiceInterface $userService) {
$this->userService = $userService;
}
public function get(\Psr\Http\Message\ResponseInterface $response, \Psr\Http\Message\RequestInterface $request){
//$user = $this->userService->get();
$response->getBody()->write("Test");
return $response;
}
}
In the example above I get the following error-message:
Non-static method userservice\webservice\controller\UsersController::get() should not be called statically in
I found a working solution how I can use PHP-DI autowiring with mapping to interfaces:
require __DIR__ . '/../vendor/autoload.php';
use userservice\core\services\UserServiceInterface;
use userservice\infrastructure\services\UserService;
use userservice\webservice\controller\UsersController;
use userservice\core\repositories\UserRepositoryInterface;
use userservice\infrastructure\repositories\UserRepository;
/**
* Mapping of classes to interfaces
*/
$definitions = [
//REPOSITORIES
UserRepositoryInterface::class => DI\get(UserRepository::class),
//SERVICES
UserServiceInterface::class => DI\get(UserService::class),
];
$builder = new DI\ContainerBuilder();
$builder->addDefinitions($definitions);
$container = $builder->build();
$app = \DI\Bridge\Slim\Bridge::create($container);
$app->get('/user', [UsersController::class, 'get']);
$app->run();