Using DI with Symfony Controller











up vote
0
down vote

favorite












I'm looking for a concrete example of implementing DI with Symfony controllers... https://symfony.com/doc/3.4/controller/service.html hasn't been much help.



Config



search_service:
class: AcmeMyBundleServicesSearchService

search_controller:
class: AcmeMyBundleControllerSearchController
arguments: ['@search_service']


Controller



// Acme/MyBundle/Controllers/SearchController.php

class SearchController extends Controller
{
public function __construct(SearchService $searchService)
{
$this->searchService = $searchService;
}
}


Gives me:



Type error: Argument 1 passed to Acme\MyBundle\Controller\SearchController::__construct() must be an instance of Acme\MyBundle\Services\SearchService, none given


Any help appreciated :)










share|improve this question


























    up vote
    0
    down vote

    favorite












    I'm looking for a concrete example of implementing DI with Symfony controllers... https://symfony.com/doc/3.4/controller/service.html hasn't been much help.



    Config



    search_service:
    class: AcmeMyBundleServicesSearchService

    search_controller:
    class: AcmeMyBundleControllerSearchController
    arguments: ['@search_service']


    Controller



    // Acme/MyBundle/Controllers/SearchController.php

    class SearchController extends Controller
    {
    public function __construct(SearchService $searchService)
    {
    $this->searchService = $searchService;
    }
    }


    Gives me:



    Type error: Argument 1 passed to Acme\MyBundle\Controller\SearchController::__construct() must be an instance of Acme\MyBundle\Services\SearchService, none given


    Any help appreciated :)










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I'm looking for a concrete example of implementing DI with Symfony controllers... https://symfony.com/doc/3.4/controller/service.html hasn't been much help.



      Config



      search_service:
      class: AcmeMyBundleServicesSearchService

      search_controller:
      class: AcmeMyBundleControllerSearchController
      arguments: ['@search_service']


      Controller



      // Acme/MyBundle/Controllers/SearchController.php

      class SearchController extends Controller
      {
      public function __construct(SearchService $searchService)
      {
      $this->searchService = $searchService;
      }
      }


      Gives me:



      Type error: Argument 1 passed to Acme\MyBundle\Controller\SearchController::__construct() must be an instance of Acme\MyBundle\Services\SearchService, none given


      Any help appreciated :)










      share|improve this question













      I'm looking for a concrete example of implementing DI with Symfony controllers... https://symfony.com/doc/3.4/controller/service.html hasn't been much help.



      Config



      search_service:
      class: AcmeMyBundleServicesSearchService

      search_controller:
      class: AcmeMyBundleControllerSearchController
      arguments: ['@search_service']


      Controller



      // Acme/MyBundle/Controllers/SearchController.php

      class SearchController extends Controller
      {
      public function __construct(SearchService $searchService)
      {
      $this->searchService = $searchService;
      }
      }


      Gives me:



      Type error: Argument 1 passed to Acme\MyBundle\Controller\SearchController::__construct() must be an instance of Acme\MyBundle\Services\SearchService, none given


      Any help appreciated :)







      symfony dependency-injection






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 7 at 10:46









      cloakedninjas

      2,49412238




      2,49412238
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote













          Your controller does not work, because you don't have a namespace. So at the start, add correct namespace, but it will still be problematic to inject parameters with manual wiring, because you extend base controller.



          Better just use autowiring, with that you won't need to define your dependencies from services.yml and it will work with controllers easily.



          Here's example



            # app/config/services.yml
          services:
          # default configuration for services in *this* file
          _defaults:
          # automatically injects dependencies in your services
          autowire: true
          # automatically registers your services as commands, event subscribers, etc.
          autoconfigure: true
          # this means you cannot fetch services directly from the container via $container->get()
          # if you need to do this, you can override this setting on individual services
          public: false

          # makes classes in src/AppBundle available to be used as services
          # this creates a service per class whose id is the fully-qualified class name
          AppBundle:
          resource: '../../src/AppBundle/*'
          # you can exclude directories or files
          # but if a service is unused, it's removed anyway
          exclude: '../../src/AppBundle/{Entity,Repository}'

          # controllers are imported separately to make sure they're public
          # and have a tag that allows actions to type-hint services
          AppBundleController:
          resource: '../../src/AppBundle/Controller'
          tags: ['controller.service_arguments']


          ps. Also, I recommend to don't extend base controller at all, because in that way you get too much dependencies you actually don't need. Better to get twig, services and everything you need by wiring them.






          share|improve this answer























          • Tried this, but seem to be having issues resolving paths... ../src/Controller where's the namespace and bundle in that path?
            – cloakedninjas
            Nov 7 at 11:07










          • @cloakedninjas Updated code for version below 4, try now, but i'm not sure why you have this "Acme prefix" before :D, is that demo app ? Do you have dir structure like /src/AppBundle ? Please add autoload section of composer.json
            – revengeance
            Nov 7 at 11:14












          • It's not Acme - but the name of our company, we have several namespaces in our repo Company1CoolBundle, Company2AwesomeBundle
            – cloakedninjas
            Nov 7 at 11:17










          • However - it's still unable to find these paths The file "../../src/MyBundle/Controller" does not exist (in: /srv/www/src/Acme/MyBundle/DependencyInjection/../Resources/config).
            – cloakedninjas
            Nov 7 at 11:19










          • @cloakedninjas It will work, when you add cottect bundle name
            – revengeance
            Nov 7 at 11:21


















          up vote
          0
          down vote



          accepted










          I had to make the follow changes to get it working for my 3.4 installation:



          Change resource relative path



          AcmeMyBundleController:
          resource: '../../Controller'
          tags: ['controller.service_arguments']


          Change 'name' of the controller to the full classname



          AcmeMyBundleControllerSearchController:
          class: AcmeMyBundleControllerSearchController
          arguments: ['@search_service']





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53187915%2fusing-di-with-symfony-controller%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote













            Your controller does not work, because you don't have a namespace. So at the start, add correct namespace, but it will still be problematic to inject parameters with manual wiring, because you extend base controller.



            Better just use autowiring, with that you won't need to define your dependencies from services.yml and it will work with controllers easily.



            Here's example



              # app/config/services.yml
            services:
            # default configuration for services in *this* file
            _defaults:
            # automatically injects dependencies in your services
            autowire: true
            # automatically registers your services as commands, event subscribers, etc.
            autoconfigure: true
            # this means you cannot fetch services directly from the container via $container->get()
            # if you need to do this, you can override this setting on individual services
            public: false

            # makes classes in src/AppBundle available to be used as services
            # this creates a service per class whose id is the fully-qualified class name
            AppBundle:
            resource: '../../src/AppBundle/*'
            # you can exclude directories or files
            # but if a service is unused, it's removed anyway
            exclude: '../../src/AppBundle/{Entity,Repository}'

            # controllers are imported separately to make sure they're public
            # and have a tag that allows actions to type-hint services
            AppBundleController:
            resource: '../../src/AppBundle/Controller'
            tags: ['controller.service_arguments']


            ps. Also, I recommend to don't extend base controller at all, because in that way you get too much dependencies you actually don't need. Better to get twig, services and everything you need by wiring them.






            share|improve this answer























            • Tried this, but seem to be having issues resolving paths... ../src/Controller where's the namespace and bundle in that path?
              – cloakedninjas
              Nov 7 at 11:07










            • @cloakedninjas Updated code for version below 4, try now, but i'm not sure why you have this "Acme prefix" before :D, is that demo app ? Do you have dir structure like /src/AppBundle ? Please add autoload section of composer.json
              – revengeance
              Nov 7 at 11:14












            • It's not Acme - but the name of our company, we have several namespaces in our repo Company1CoolBundle, Company2AwesomeBundle
              – cloakedninjas
              Nov 7 at 11:17










            • However - it's still unable to find these paths The file "../../src/MyBundle/Controller" does not exist (in: /srv/www/src/Acme/MyBundle/DependencyInjection/../Resources/config).
              – cloakedninjas
              Nov 7 at 11:19










            • @cloakedninjas It will work, when you add cottect bundle name
              – revengeance
              Nov 7 at 11:21















            up vote
            1
            down vote













            Your controller does not work, because you don't have a namespace. So at the start, add correct namespace, but it will still be problematic to inject parameters with manual wiring, because you extend base controller.



            Better just use autowiring, with that you won't need to define your dependencies from services.yml and it will work with controllers easily.



            Here's example



              # app/config/services.yml
            services:
            # default configuration for services in *this* file
            _defaults:
            # automatically injects dependencies in your services
            autowire: true
            # automatically registers your services as commands, event subscribers, etc.
            autoconfigure: true
            # this means you cannot fetch services directly from the container via $container->get()
            # if you need to do this, you can override this setting on individual services
            public: false

            # makes classes in src/AppBundle available to be used as services
            # this creates a service per class whose id is the fully-qualified class name
            AppBundle:
            resource: '../../src/AppBundle/*'
            # you can exclude directories or files
            # but if a service is unused, it's removed anyway
            exclude: '../../src/AppBundle/{Entity,Repository}'

            # controllers are imported separately to make sure they're public
            # and have a tag that allows actions to type-hint services
            AppBundleController:
            resource: '../../src/AppBundle/Controller'
            tags: ['controller.service_arguments']


            ps. Also, I recommend to don't extend base controller at all, because in that way you get too much dependencies you actually don't need. Better to get twig, services and everything you need by wiring them.






            share|improve this answer























            • Tried this, but seem to be having issues resolving paths... ../src/Controller where's the namespace and bundle in that path?
              – cloakedninjas
              Nov 7 at 11:07










            • @cloakedninjas Updated code for version below 4, try now, but i'm not sure why you have this "Acme prefix" before :D, is that demo app ? Do you have dir structure like /src/AppBundle ? Please add autoload section of composer.json
              – revengeance
              Nov 7 at 11:14












            • It's not Acme - but the name of our company, we have several namespaces in our repo Company1CoolBundle, Company2AwesomeBundle
              – cloakedninjas
              Nov 7 at 11:17










            • However - it's still unable to find these paths The file "../../src/MyBundle/Controller" does not exist (in: /srv/www/src/Acme/MyBundle/DependencyInjection/../Resources/config).
              – cloakedninjas
              Nov 7 at 11:19










            • @cloakedninjas It will work, when you add cottect bundle name
              – revengeance
              Nov 7 at 11:21













            up vote
            1
            down vote










            up vote
            1
            down vote









            Your controller does not work, because you don't have a namespace. So at the start, add correct namespace, but it will still be problematic to inject parameters with manual wiring, because you extend base controller.



            Better just use autowiring, with that you won't need to define your dependencies from services.yml and it will work with controllers easily.



            Here's example



              # app/config/services.yml
            services:
            # default configuration for services in *this* file
            _defaults:
            # automatically injects dependencies in your services
            autowire: true
            # automatically registers your services as commands, event subscribers, etc.
            autoconfigure: true
            # this means you cannot fetch services directly from the container via $container->get()
            # if you need to do this, you can override this setting on individual services
            public: false

            # makes classes in src/AppBundle available to be used as services
            # this creates a service per class whose id is the fully-qualified class name
            AppBundle:
            resource: '../../src/AppBundle/*'
            # you can exclude directories or files
            # but if a service is unused, it's removed anyway
            exclude: '../../src/AppBundle/{Entity,Repository}'

            # controllers are imported separately to make sure they're public
            # and have a tag that allows actions to type-hint services
            AppBundleController:
            resource: '../../src/AppBundle/Controller'
            tags: ['controller.service_arguments']


            ps. Also, I recommend to don't extend base controller at all, because in that way you get too much dependencies you actually don't need. Better to get twig, services and everything you need by wiring them.






            share|improve this answer














            Your controller does not work, because you don't have a namespace. So at the start, add correct namespace, but it will still be problematic to inject parameters with manual wiring, because you extend base controller.



            Better just use autowiring, with that you won't need to define your dependencies from services.yml and it will work with controllers easily.



            Here's example



              # app/config/services.yml
            services:
            # default configuration for services in *this* file
            _defaults:
            # automatically injects dependencies in your services
            autowire: true
            # automatically registers your services as commands, event subscribers, etc.
            autoconfigure: true
            # this means you cannot fetch services directly from the container via $container->get()
            # if you need to do this, you can override this setting on individual services
            public: false

            # makes classes in src/AppBundle available to be used as services
            # this creates a service per class whose id is the fully-qualified class name
            AppBundle:
            resource: '../../src/AppBundle/*'
            # you can exclude directories or files
            # but if a service is unused, it's removed anyway
            exclude: '../../src/AppBundle/{Entity,Repository}'

            # controllers are imported separately to make sure they're public
            # and have a tag that allows actions to type-hint services
            AppBundleController:
            resource: '../../src/AppBundle/Controller'
            tags: ['controller.service_arguments']


            ps. Also, I recommend to don't extend base controller at all, because in that way you get too much dependencies you actually don't need. Better to get twig, services and everything you need by wiring them.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 7 at 11:13

























            answered Nov 7 at 11:02









            revengeance

            461210




            461210












            • Tried this, but seem to be having issues resolving paths... ../src/Controller where's the namespace and bundle in that path?
              – cloakedninjas
              Nov 7 at 11:07










            • @cloakedninjas Updated code for version below 4, try now, but i'm not sure why you have this "Acme prefix" before :D, is that demo app ? Do you have dir structure like /src/AppBundle ? Please add autoload section of composer.json
              – revengeance
              Nov 7 at 11:14












            • It's not Acme - but the name of our company, we have several namespaces in our repo Company1CoolBundle, Company2AwesomeBundle
              – cloakedninjas
              Nov 7 at 11:17










            • However - it's still unable to find these paths The file "../../src/MyBundle/Controller" does not exist (in: /srv/www/src/Acme/MyBundle/DependencyInjection/../Resources/config).
              – cloakedninjas
              Nov 7 at 11:19










            • @cloakedninjas It will work, when you add cottect bundle name
              – revengeance
              Nov 7 at 11:21


















            • Tried this, but seem to be having issues resolving paths... ../src/Controller where's the namespace and bundle in that path?
              – cloakedninjas
              Nov 7 at 11:07










            • @cloakedninjas Updated code for version below 4, try now, but i'm not sure why you have this "Acme prefix" before :D, is that demo app ? Do you have dir structure like /src/AppBundle ? Please add autoload section of composer.json
              – revengeance
              Nov 7 at 11:14












            • It's not Acme - but the name of our company, we have several namespaces in our repo Company1CoolBundle, Company2AwesomeBundle
              – cloakedninjas
              Nov 7 at 11:17










            • However - it's still unable to find these paths The file "../../src/MyBundle/Controller" does not exist (in: /srv/www/src/Acme/MyBundle/DependencyInjection/../Resources/config).
              – cloakedninjas
              Nov 7 at 11:19










            • @cloakedninjas It will work, when you add cottect bundle name
              – revengeance
              Nov 7 at 11:21
















            Tried this, but seem to be having issues resolving paths... ../src/Controller where's the namespace and bundle in that path?
            – cloakedninjas
            Nov 7 at 11:07




            Tried this, but seem to be having issues resolving paths... ../src/Controller where's the namespace and bundle in that path?
            – cloakedninjas
            Nov 7 at 11:07












            @cloakedninjas Updated code for version below 4, try now, but i'm not sure why you have this "Acme prefix" before :D, is that demo app ? Do you have dir structure like /src/AppBundle ? Please add autoload section of composer.json
            – revengeance
            Nov 7 at 11:14






            @cloakedninjas Updated code for version below 4, try now, but i'm not sure why you have this "Acme prefix" before :D, is that demo app ? Do you have dir structure like /src/AppBundle ? Please add autoload section of composer.json
            – revengeance
            Nov 7 at 11:14














            It's not Acme - but the name of our company, we have several namespaces in our repo Company1CoolBundle, Company2AwesomeBundle
            – cloakedninjas
            Nov 7 at 11:17




            It's not Acme - but the name of our company, we have several namespaces in our repo Company1CoolBundle, Company2AwesomeBundle
            – cloakedninjas
            Nov 7 at 11:17












            However - it's still unable to find these paths The file "../../src/MyBundle/Controller" does not exist (in: /srv/www/src/Acme/MyBundle/DependencyInjection/../Resources/config).
            – cloakedninjas
            Nov 7 at 11:19




            However - it's still unable to find these paths The file "../../src/MyBundle/Controller" does not exist (in: /srv/www/src/Acme/MyBundle/DependencyInjection/../Resources/config).
            – cloakedninjas
            Nov 7 at 11:19












            @cloakedninjas It will work, when you add cottect bundle name
            – revengeance
            Nov 7 at 11:21




            @cloakedninjas It will work, when you add cottect bundle name
            – revengeance
            Nov 7 at 11:21












            up vote
            0
            down vote



            accepted










            I had to make the follow changes to get it working for my 3.4 installation:



            Change resource relative path



            AcmeMyBundleController:
            resource: '../../Controller'
            tags: ['controller.service_arguments']


            Change 'name' of the controller to the full classname



            AcmeMyBundleControllerSearchController:
            class: AcmeMyBundleControllerSearchController
            arguments: ['@search_service']





            share|improve this answer

























              up vote
              0
              down vote



              accepted










              I had to make the follow changes to get it working for my 3.4 installation:



              Change resource relative path



              AcmeMyBundleController:
              resource: '../../Controller'
              tags: ['controller.service_arguments']


              Change 'name' of the controller to the full classname



              AcmeMyBundleControllerSearchController:
              class: AcmeMyBundleControllerSearchController
              arguments: ['@search_service']





              share|improve this answer























                up vote
                0
                down vote



                accepted







                up vote
                0
                down vote



                accepted






                I had to make the follow changes to get it working for my 3.4 installation:



                Change resource relative path



                AcmeMyBundleController:
                resource: '../../Controller'
                tags: ['controller.service_arguments']


                Change 'name' of the controller to the full classname



                AcmeMyBundleControllerSearchController:
                class: AcmeMyBundleControllerSearchController
                arguments: ['@search_service']





                share|improve this answer












                I had to make the follow changes to get it working for my 3.4 installation:



                Change resource relative path



                AcmeMyBundleController:
                resource: '../../Controller'
                tags: ['controller.service_arguments']


                Change 'name' of the controller to the full classname



                AcmeMyBundleControllerSearchController:
                class: AcmeMyBundleControllerSearchController
                arguments: ['@search_service']






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 7 at 13:18









                cloakedninjas

                2,49412238




                2,49412238






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53187915%2fusing-di-with-symfony-controller%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Xamarin.form Move up view when keyboard appear

                    Post-Redirect-Get with Spring WebFlux and Thymeleaf

                    Anylogic : not able to use stopDelay()