Skip to content

Instantly share code, notes, and snippets.

@devjack
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devjack/9701954 to your computer and use it in GitHub Desktop.
Save devjack/9701954 to your computer and use it in GitHub Desktop.
ZF2 traits example: UserServiceAwareTrait
<?php
namespace SampleService\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
// Each 'AwareTrait' is expected to be configured by the controllers factory
use SampleService\Service\Feature\UserServiceAwareTrait;
use SampleService\Service\Feature\UserFilterServiceAwareTrait;
use SampleService\Form\Feature\FilterFormAwareTrait;
class UserController extends AbstractActionController
{
use UserServiceAwareTrait; // a.k.a. This controller uses the UserService
use UserFilterServiceAwareTrait;
use FilterFormAwareTrait;
// Some action methods go here
}
<?php
namespace SampleService\Controller\Service;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use SampleService\Controller\Usercontroller;
class UserControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
/** @var ServiceLocatorInterface $serviceLocator */
$serviceLocator = $serviceLocator->getServiceLocator();
$controller = new UserController();
// The factory is responsible for initialising (via the SL)
// each of the controllers dependencies.
$controller->setFilterForm(
$serviceLocator->get('FormElementManager')->get('SampleService\Form\FilterForm')
);
$controller->setUserService(
$serviceLocator->get('SampleService\Service\UserService')
);
$controller->setUserFilterService(
$serviceLocator->get('SampleService\Service\UserFilterService')
);
return $controller;
}
}
<?php
namespace SampleService\Service\Feature;
use SampleService\Service\UserService;
use Zend\Stdlib\Exception\LogicException;
// This trait exposes the UserService to any 'aware' class.
// Controllers will most commonly use this trait.
trait UserServiceAwareTrait {
/**
* @var UserService
*/
protected $userService;
public function setUserService($userService)
{
$this->userService = $userService;
}
public function getUserService()
{
if(null === $this->userService) {
throw new LogicException("User service must be defined");
}
return $this->userService;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment