Last active
March 18, 2016 11:37
-
-
Save webdevilopers/ea6deef7d7f4f4355fab to your computer and use it in GitHub Desktop.
Inject Token Storage into Command
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 Plusquam\Bundle\ContractBundle\Controller; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; | |
use Symfony\Component\HttpFoundation\Response; | |
use Plusquam\Bundle\ContractBundle\Entity\Contract; | |
use Plusquam\Bundle\ContractBundle\Command\OpenContractCommand; | |
use Plusquam\Bundle\ContractBundle\Form\OpenContract as OpenContractForm; | |
class ContractController extends Controller | |
{ | |
/** | |
* @Route("/qis/contract/open", name="qis_contract_open") | |
* @Security("has_role('ROLE_QIS_CONTRACT_EDITOR')") | |
* Template() | |
*/ | |
public function openAction() | |
{ | |
$openContractCommand = new OpenContractCommand(); | |
$tokenStorage = $this->get('security.token_storage'); | |
$user = $tokenStorage->getToken()->getUser(); | |
$branch = $user->getBranch(); | |
$openContractCommand->branch = $branch; | |
$form = $this->createForm(new OpenContractForm(), $openContractCommand); | |
$form->handleRequest($this->getRequest()); | |
if ($form->isValid()) { | |
$openContractHandler = $this->get('open_contract_handler'); | |
$openContractHandler->handle($openContractCommand); | |
} | |
return $this->render('PlusquamContractBundle:Contract:open.html.twig', array( | |
'form' => $form->createView() | |
)); | |
} | |
} |
Agree with @veewee.
Instead of injecting the branch in the command, you should use the branch Id. That way the handler is responsible of loading the branch from the repository.
On another note, instead of fetching the handler directly, should you not pass the command to the command bus which will pass it to the right handler(s)?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Totally agree @veewee ! In the end I shouldn't think about setting defaults on the command directly.
Instead - in my use case - the data comes from the form. Currently the Controller sets the data on the command.
But it looks like the best idea is actually to inject the
tokenStorage
into the form and PRE_SET thebranch
with the User data from thetokenStorage
.As recommended by @webmozart on the tutorial by @khepin here:
http://sf.khepin.com/2012/10/user-dependent-forms-in-symfony2/#comment-7602