I have read the "Service Container" entry--and nearly every linked entry--in the Symfony 4 docs. I have tackled this issue on two separate occasions spending 4-6 hours each time. I clearly just don't get it...please help!
I want to use dependency injection to use a service (SessionInterface) in a model (User) but I do not want to use the model constructor as then I would need to inject the dependency each time I hydrate and instantiate the model. I think I should be able to use method call and setter injection to meet this criteria.
services:
_defaults:
autowire: true
autoconfigure: true
public: false
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
namespace App\Model\System\User;
use App\Model\System\Client\Client;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\User\{EquatableInterface, UserInterface};
class User implements EquatableInterface, UserInterface
{
private $session;
public function __construct(array $properties)
{
// stuff
}
public function clientAssumed(): Client
{
return $this->session->get('foo', 'bar');
}
/**
* @required
*
* @param SessionInterface $session
*/
public function setSession(SessionInterface $session)
{
$this->session = $session;
}
}
namespace App\Controller\Core;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class CoreBase extends AbstractController
{
/**
* Displays authenticated User landing page.
*
* @Route("/home", name="core_home")
*
* @param Security $security
*
* @return Response
*/
public function landing(Security $security): Response
{
$data = [
'client' => $security->getUser()->clientAssumed(),
];
return $this->render('core/landing.html.twig', $data);
}
}
php bin/console debug:container 'App\Model\System\User\User'
.
Information for Service "App\Model\System\User\User"
====================================================
---------------- ----------------------------
Option Value
---------------- ----------------------------
Service ID App\Model\System\User\User
Class App\Model\System\User\User
Tags -
Calls setSession
Public no
Synthetic no
Lazy no
Shared yes
Abstract no
Autowired yes
Autoconfigured yes
---------------- ----------------------------
Too few arguments to function App\Model\System\User\User::setSession(), 0 passed in /srv/http/wwwroot/gw4/src/Controller/Core/CoreBase.php on line 25 and exactly 1 expected