Jan28

Tagged in:Comments:

Symfony3 Container Dependency Injection

It’s 2016, you can use trait which will help you extend same class with multiple libraries.

I keep seeing container class get extended into another class, which then extends to another, before you know it you have extended 5 different classes just to use libraries.

What if you can include 5 different libraries into 1 object without extending? Well you can use it with php5.4 trait feature.

Container dependency injection trait class

    
    namespace iBasit\ToolsBundle\Utils\Lib;
    
    use Doctrine\Bundle\DoctrineBundle\Registry;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    trait Container
    {
        private $container;
    
        public function setContainer (ContainerInterface $container)
        {
            $this->container = $container;
        }
    
        /**
         * Shortcut to return the Doctrine Registry service.
         *
         * @return Registry
         *
         * @throws \LogicException If DoctrineBundle is not available
         */
        protected function getDoctrine()
        {
            if (!$this->container->has('doctrine')) {
                throw new \LogicException('The DoctrineBundle is not registered in your application.');
            }
    
            return $this->container->get('doctrine');
        }
    
        /**
         * Get a user from the Security Token Storage.
         *
         * @return mixed
         *
         * @throws \LogicException If SecurityBundle is not available
         *
         * @see TokenInterface::getUser()
         */
        protected function getUser()
        {
            if (!$this->container->has('security.token_storage')) {
                throw new \LogicException('The SecurityBundle is not registered in your application.');
            }
    
            if (null === $token = $this->container->get('security.token_storage')->getToken()) {
                return;
            }
    
            if (!is_object($user = $token->getUser())) {
                // e.g. anonymous authentication
                return;
            }
    
            return $user;
        }
    
        /**
         * Returns true if the service id is defined.
         *
         * @param string $id The service id
         *
         * @return bool true if the service id is defined, false otherwise
         */
        protected function has ($id)
        {
            return $this->container->has($id);
        }
    
        /**
         * Gets a container service by its id.
         *
         * @param string $id The service id
         *
         * @return object The service
         */
        protected function get ($id)
        {
            if ('request' === $id)
            {
                @trigger_error('The "request" service is deprecated and will be removed in 3.0. Add a typehint for Symfony\\Component\\HttpFoundation\\Request to your controller parameters to retrieve the request instead.', E_USER_DEPRECATED);
            }
    
            return $this->container->get($id);
        }
    
        /**
         * Gets a container configuration parameter by its name.
         *
         * @param string $name The parameter name
         *
         * @return mixed
         */
        protected function getParameter ($name)
        {
            return $this->container->getParameter($name);
        }
    }

Your custom object, which will be service.

    namespace AppBundle\Utils;
    
    use iBasit\ToolsBundle\Utils\Lib\Container;
    
    class myObject
    {
        use Container;
    }

Your object service settings

     myObject: 
            class: AppBundle\Utils\myObject
            calls:
                - [setContainer, ["@service_container"]]

Call your service in controller

    $myObject = $this->get('myObject');

2 Comments


  1. Fatal error: Uncaught Error: Call to undefined function ereg() in /home/u840270379/domains/basit.me/public_html/wp-content/themes/basit/functions.php:329 Stack trace: #0 /home/u840270379/domains/basit.me/public_html/wp-content/themes/basit/comments.php(69): sandbox_commenter_link() #1 /home/u840270379/domains/basit.me/public_html/wp-includes/comment-template.php(1618): require('/home/u84027037...') #2 /home/u840270379/domains/basit.me/public_html/wp-content/themes/basit/single.php(52): comments_template() #3 /home/u840270379/domains/basit.me/public_html/wp-includes/template-loader.php(106): include('/home/u84027037...') #4 /home/u840270379/domains/basit.me/public_html/wp-blog-header.php(19): require_once('/home/u84027037...') #5 /home/u840270379/domains/basit.me/public_html/index.php(17): require('/home/u84027037...') #6 {main} thrown in /home/u840270379/domains/basit.me/public_html/wp-content/themes/basit/functions.php on line 329
    WordPress › Error

    There has been a critical error on this website.

    Learn more about troubleshooting WordPress.