Created
August 19, 2014 09:04
-
-
Save tentacode/ef4d19b390a599be74a6 to your computer and use it in GitHub Desktop.
PHP DI + Trait + Symfony service === <3 ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tentacode\App\Security; | |
trait ConnectedUser | |
{ | |
/** | |
* @Inject | |
* @var Symfony\Component\Security\Core\SecurityContext | |
*/ | |
private $securityContext; | |
public function getConnectedUser() | |
{ | |
$token = $this->securityContext->getToken(); | |
if (!$token) { | |
throw new \RuntimeException('No user is connected.'); | |
} | |
return $token->getUser(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
return [ | |
'Symfony\Component\Security\Core\SecurityContext' => DI\link('security.context'), | |
// ... | |
]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tentacode\App\Controller\Person; | |
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; | |
use Tentacode\App\Security\ConnectedUser; | |
use Tentacode\App\Templating\Templating; | |
use Tentacode\Domain\Person\PersonRepository; | |
use Tentacode\Domain\User; | |
class ProfileController | |
{ | |
use ConnectedUser; | |
protected $templating; | |
protected $personRepository; | |
public function __construct(Templating $templating, PersonRepository $personRepository) | |
{ | |
$this->templating = $templating; | |
$this->personRepository = $personRepository; | |
} | |
public function myProfileAction() | |
{ | |
$user = $this->getConnectedUser(); | |
return $this->templating->render('TentacodeAppBundle:Person:profile.html.twig', [ | |
'user' => $user | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
yeah, that's what I'll be doing in practice, @Inject on properties, and utility services