Laravel: dependency injection in commands2019 Community Moderator ElectionHow can I mock a class that is used in an artisan command for testing?Which .NET Dependency Injection frameworks are worth looking into?How can I prevent SQL injection in PHP?What is dependency injection?Dependency Injection vs Factory PatternWhat are the downsides to using Dependency Injection?Inversion of Control vs Dependency InjectionWhy does one use dependency injection?Laravel Composer error Uncaught ReflectionException: Class log does not exist in Container.php:738What is `HtmlString` used for in Laravel?PHP symfony4: Dependency injection inside KernelTestCase for command

Word for a person who has no opinion about whether god exists

Was Luke Skywalker the leader of the Rebel forces on Hoth?

How can I ensure my trip to the UK will not have to be cancelled because of Brexit?

What are some noteworthy "mic-drop" moments in math?

What Happens when Passenger Refuses to Fly Boeing 737 Max?

Does the nature of the Apocalypse in The Umbrella Academy change from the first to the last episode?

What wound would be of little consequence to a biped but terrible for a quadruped?

NASA's RS-25 Engines shut down time

Makefile strange variable substitution

Difference on montgomery curve equation between EFD and RFC7748

Plausibility of Mushroom Buildings

meaning and function of 幸 in "则幸分我一杯羹"

List elements digit difference sort

Single word request: Harming the benefactor

What problems would a superhuman have whose skin is constantly hot?

Is "conspicuously missing" or "conspicuously" the subject of this sentence?

Is it possible to avoid unpacking when merging Association?

Is it necessary to separate DC power cables and data cables?

Error during using callback start_page_number in lualatex

Doesn't allowing a user mode program to access kernel space memory and execute the IN and OUT instructions defeat the purpose of having CPU modes?

Motivation for Zeta Function of an Algebraic Variety

In the late 1940’s to early 1950’s what technology was available that could melt a LOT of ice?

How can The Temple of Elementary Evil reliably protect itself against kinetic bombardment?

Is "history" a male-biased word ("his+story")?



Laravel: dependency injection in commands



2019 Community Moderator ElectionHow can I mock a class that is used in an artisan command for testing?Which .NET Dependency Injection frameworks are worth looking into?How can I prevent SQL injection in PHP?What is dependency injection?Dependency Injection vs Factory PatternWhat are the downsides to using Dependency Injection?Inversion of Control vs Dependency InjectionWhy does one use dependency injection?Laravel Composer error Uncaught ReflectionException: Class log does not exist in Container.php:738What is `HtmlString` used for in Laravel?PHP symfony4: Dependency injection inside KernelTestCase for command










4















Is dependency injection of a custom class in a command possible?



I'm trying this:



<?php

namespace vendorpackageCommands;

use IlluminateConsoleCommand;
use vendorpackageModelsLog;
use vendorpackageUpdatesUpdateStatistics;

class UpdatePublishmentStats extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'vendorname:updatePublishmentStats';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Updates Twitter followers & Facebook page likes';

/**
* Contact implementation
* @var vendorpackageUpdateUpdateStatistics
*/
protected $stats;

/**
* Create a new command instance.
*
* @return void
*/
public function __construct(
Log $log,
UpdateStatistics $stats
)
parent::__construct();
$this->log = $log;
$this->stats = $stats;



But when I try to do this:



public function handle()

$this->stats->updateFbStats();




I suddenly get Segmentation fault: 11



When I delete the use vendorpackageUpdatesUpdateStatistics; part, I don't get that error.



So what am I doing wrong here? Is it not possible to use dependency injection in a command?










share|improve this question


























    4















    Is dependency injection of a custom class in a command possible?



    I'm trying this:



    <?php

    namespace vendorpackageCommands;

    use IlluminateConsoleCommand;
    use vendorpackageModelsLog;
    use vendorpackageUpdatesUpdateStatistics;

    class UpdatePublishmentStats extends Command
    {
    /**
    * The name and signature of the console command.
    *
    * @var string
    */
    protected $signature = 'vendorname:updatePublishmentStats';

    /**
    * The console command description.
    *
    * @var string
    */
    protected $description = 'Updates Twitter followers & Facebook page likes';

    /**
    * Contact implementation
    * @var vendorpackageUpdateUpdateStatistics
    */
    protected $stats;

    /**
    * Create a new command instance.
    *
    * @return void
    */
    public function __construct(
    Log $log,
    UpdateStatistics $stats
    )
    parent::__construct();
    $this->log = $log;
    $this->stats = $stats;



    But when I try to do this:



    public function handle()

    $this->stats->updateFbStats();




    I suddenly get Segmentation fault: 11



    When I delete the use vendorpackageUpdatesUpdateStatistics; part, I don't get that error.



    So what am I doing wrong here? Is it not possible to use dependency injection in a command?










    share|improve this question
























      4












      4








      4








      Is dependency injection of a custom class in a command possible?



      I'm trying this:



      <?php

      namespace vendorpackageCommands;

      use IlluminateConsoleCommand;
      use vendorpackageModelsLog;
      use vendorpackageUpdatesUpdateStatistics;

      class UpdatePublishmentStats extends Command
      {
      /**
      * The name and signature of the console command.
      *
      * @var string
      */
      protected $signature = 'vendorname:updatePublishmentStats';

      /**
      * The console command description.
      *
      * @var string
      */
      protected $description = 'Updates Twitter followers & Facebook page likes';

      /**
      * Contact implementation
      * @var vendorpackageUpdateUpdateStatistics
      */
      protected $stats;

      /**
      * Create a new command instance.
      *
      * @return void
      */
      public function __construct(
      Log $log,
      UpdateStatistics $stats
      )
      parent::__construct();
      $this->log = $log;
      $this->stats = $stats;



      But when I try to do this:



      public function handle()

      $this->stats->updateFbStats();




      I suddenly get Segmentation fault: 11



      When I delete the use vendorpackageUpdatesUpdateStatistics; part, I don't get that error.



      So what am I doing wrong here? Is it not possible to use dependency injection in a command?










      share|improve this question














      Is dependency injection of a custom class in a command possible?



      I'm trying this:



      <?php

      namespace vendorpackageCommands;

      use IlluminateConsoleCommand;
      use vendorpackageModelsLog;
      use vendorpackageUpdatesUpdateStatistics;

      class UpdatePublishmentStats extends Command
      {
      /**
      * The name and signature of the console command.
      *
      * @var string
      */
      protected $signature = 'vendorname:updatePublishmentStats';

      /**
      * The console command description.
      *
      * @var string
      */
      protected $description = 'Updates Twitter followers & Facebook page likes';

      /**
      * Contact implementation
      * @var vendorpackageUpdateUpdateStatistics
      */
      protected $stats;

      /**
      * Create a new command instance.
      *
      * @return void
      */
      public function __construct(
      Log $log,
      UpdateStatistics $stats
      )
      parent::__construct();
      $this->log = $log;
      $this->stats = $stats;



      But when I try to do this:



      public function handle()

      $this->stats->updateFbStats();




      I suddenly get Segmentation fault: 11



      When I delete the use vendorpackageUpdatesUpdateStatistics; part, I don't get that error.



      So what am I doing wrong here? Is it not possible to use dependency injection in a command?







      php laravel dependency-injection laravel-5






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jun 5 '16 at 22:59









      RW24RW24

      3861315




      3861315






















          2 Answers
          2






          active

          oldest

          votes


















          0














          According to the Command Structure section of 5.2 documentation (https://laravel.com/docs/5.2/artisan#writing-commands):




          "Note that we are able to inject any dependencies we need into the command's constructor. The Laravel service container will automatically inject all dependencies type-hinted in the constructor."




          So I think you're good there, as far as the capability being present and available.



          As for getting it to work, for me the segfault points to something wrong with the UpdateStats class, how it's referenced in the service container, or how its being resolved from the service container.



          I don't have a definitive answer, but what I would do is try another class and see if I could localize the issue to this particular class, or if the problem happens with others, and then try and debug from there.



          Also, if you just can't get that to work, the app() function will resolve items from the service container when you want (although looking through the 5.2 docs I don't see it anymore, so it may be deprecated - I do see $this->app->make() however).



          This may work for you if nothing else does:



          public function __construct(
          Log $log,
          )
          parent::__construct();
          $this->log = $log;
          $this->stats = app(UpdateStatistics::class);



          My guess is, however, that you will get a segfault with this as well, as it should try resolving the same class the same way. If you do, then at least the error is a little clearer, and unrelated to auto-injecting feature.



          Hope that at least helps a little.




          Update on the app() function



          So the app() function does not appear to be documented, but I have 5.2 installed right now and the helpers.php file in Illuminate/Foundation definitely has the function:



          if (! function_exists('app')) 
          /**
          * Get the available container instance.
          *
          * @param string $make
          * @param array $parameters
          * @return mixed


          Unfortunately the API documentation doesn't include any of the helper functions, but the current master, 5.2, and 5.3 versions of the file on Github all have the function:



          • https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/helpers.php#L91

          • https://github.com/laravel/framework/blob/5.3/src/Illuminate/Foundation/helpers.php#L91

          • https://github.com/laravel/framework/blob/5.2/src/Illuminate/Foundation/helpers.php#L91





          share|improve this answer
































            0














            You can inject any service in the handle method:




            Note that we are able to inject any dependencies we need into the command's handle method.




            Source: https://laravel.com/docs/5.8/artisan#command-structure






            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',
              autoActivateHeartbeat: false,
              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%2f37647614%2flaravel-dependency-injection-in-commands%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









              0














              According to the Command Structure section of 5.2 documentation (https://laravel.com/docs/5.2/artisan#writing-commands):




              "Note that we are able to inject any dependencies we need into the command's constructor. The Laravel service container will automatically inject all dependencies type-hinted in the constructor."




              So I think you're good there, as far as the capability being present and available.



              As for getting it to work, for me the segfault points to something wrong with the UpdateStats class, how it's referenced in the service container, or how its being resolved from the service container.



              I don't have a definitive answer, but what I would do is try another class and see if I could localize the issue to this particular class, or if the problem happens with others, and then try and debug from there.



              Also, if you just can't get that to work, the app() function will resolve items from the service container when you want (although looking through the 5.2 docs I don't see it anymore, so it may be deprecated - I do see $this->app->make() however).



              This may work for you if nothing else does:



              public function __construct(
              Log $log,
              )
              parent::__construct();
              $this->log = $log;
              $this->stats = app(UpdateStatistics::class);



              My guess is, however, that you will get a segfault with this as well, as it should try resolving the same class the same way. If you do, then at least the error is a little clearer, and unrelated to auto-injecting feature.



              Hope that at least helps a little.




              Update on the app() function



              So the app() function does not appear to be documented, but I have 5.2 installed right now and the helpers.php file in Illuminate/Foundation definitely has the function:



              if (! function_exists('app')) 
              /**
              * Get the available container instance.
              *
              * @param string $make
              * @param array $parameters
              * @return mixed


              Unfortunately the API documentation doesn't include any of the helper functions, but the current master, 5.2, and 5.3 versions of the file on Github all have the function:



              • https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/helpers.php#L91

              • https://github.com/laravel/framework/blob/5.3/src/Illuminate/Foundation/helpers.php#L91

              • https://github.com/laravel/framework/blob/5.2/src/Illuminate/Foundation/helpers.php#L91





              share|improve this answer





























                0














                According to the Command Structure section of 5.2 documentation (https://laravel.com/docs/5.2/artisan#writing-commands):




                "Note that we are able to inject any dependencies we need into the command's constructor. The Laravel service container will automatically inject all dependencies type-hinted in the constructor."




                So I think you're good there, as far as the capability being present and available.



                As for getting it to work, for me the segfault points to something wrong with the UpdateStats class, how it's referenced in the service container, or how its being resolved from the service container.



                I don't have a definitive answer, but what I would do is try another class and see if I could localize the issue to this particular class, or if the problem happens with others, and then try and debug from there.



                Also, if you just can't get that to work, the app() function will resolve items from the service container when you want (although looking through the 5.2 docs I don't see it anymore, so it may be deprecated - I do see $this->app->make() however).



                This may work for you if nothing else does:



                public function __construct(
                Log $log,
                )
                parent::__construct();
                $this->log = $log;
                $this->stats = app(UpdateStatistics::class);



                My guess is, however, that you will get a segfault with this as well, as it should try resolving the same class the same way. If you do, then at least the error is a little clearer, and unrelated to auto-injecting feature.



                Hope that at least helps a little.




                Update on the app() function



                So the app() function does not appear to be documented, but I have 5.2 installed right now and the helpers.php file in Illuminate/Foundation definitely has the function:



                if (! function_exists('app')) 
                /**
                * Get the available container instance.
                *
                * @param string $make
                * @param array $parameters
                * @return mixed


                Unfortunately the API documentation doesn't include any of the helper functions, but the current master, 5.2, and 5.3 versions of the file on Github all have the function:



                • https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/helpers.php#L91

                • https://github.com/laravel/framework/blob/5.3/src/Illuminate/Foundation/helpers.php#L91

                • https://github.com/laravel/framework/blob/5.2/src/Illuminate/Foundation/helpers.php#L91





                share|improve this answer



























                  0












                  0








                  0







                  According to the Command Structure section of 5.2 documentation (https://laravel.com/docs/5.2/artisan#writing-commands):




                  "Note that we are able to inject any dependencies we need into the command's constructor. The Laravel service container will automatically inject all dependencies type-hinted in the constructor."




                  So I think you're good there, as far as the capability being present and available.



                  As for getting it to work, for me the segfault points to something wrong with the UpdateStats class, how it's referenced in the service container, or how its being resolved from the service container.



                  I don't have a definitive answer, but what I would do is try another class and see if I could localize the issue to this particular class, or if the problem happens with others, and then try and debug from there.



                  Also, if you just can't get that to work, the app() function will resolve items from the service container when you want (although looking through the 5.2 docs I don't see it anymore, so it may be deprecated - I do see $this->app->make() however).



                  This may work for you if nothing else does:



                  public function __construct(
                  Log $log,
                  )
                  parent::__construct();
                  $this->log = $log;
                  $this->stats = app(UpdateStatistics::class);



                  My guess is, however, that you will get a segfault with this as well, as it should try resolving the same class the same way. If you do, then at least the error is a little clearer, and unrelated to auto-injecting feature.



                  Hope that at least helps a little.




                  Update on the app() function



                  So the app() function does not appear to be documented, but I have 5.2 installed right now and the helpers.php file in Illuminate/Foundation definitely has the function:



                  if (! function_exists('app')) 
                  /**
                  * Get the available container instance.
                  *
                  * @param string $make
                  * @param array $parameters
                  * @return mixed


                  Unfortunately the API documentation doesn't include any of the helper functions, but the current master, 5.2, and 5.3 versions of the file on Github all have the function:



                  • https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/helpers.php#L91

                  • https://github.com/laravel/framework/blob/5.3/src/Illuminate/Foundation/helpers.php#L91

                  • https://github.com/laravel/framework/blob/5.2/src/Illuminate/Foundation/helpers.php#L91





                  share|improve this answer















                  According to the Command Structure section of 5.2 documentation (https://laravel.com/docs/5.2/artisan#writing-commands):




                  "Note that we are able to inject any dependencies we need into the command's constructor. The Laravel service container will automatically inject all dependencies type-hinted in the constructor."




                  So I think you're good there, as far as the capability being present and available.



                  As for getting it to work, for me the segfault points to something wrong with the UpdateStats class, how it's referenced in the service container, or how its being resolved from the service container.



                  I don't have a definitive answer, but what I would do is try another class and see if I could localize the issue to this particular class, or if the problem happens with others, and then try and debug from there.



                  Also, if you just can't get that to work, the app() function will resolve items from the service container when you want (although looking through the 5.2 docs I don't see it anymore, so it may be deprecated - I do see $this->app->make() however).



                  This may work for you if nothing else does:



                  public function __construct(
                  Log $log,
                  )
                  parent::__construct();
                  $this->log = $log;
                  $this->stats = app(UpdateStatistics::class);



                  My guess is, however, that you will get a segfault with this as well, as it should try resolving the same class the same way. If you do, then at least the error is a little clearer, and unrelated to auto-injecting feature.



                  Hope that at least helps a little.




                  Update on the app() function



                  So the app() function does not appear to be documented, but I have 5.2 installed right now and the helpers.php file in Illuminate/Foundation definitely has the function:



                  if (! function_exists('app')) 
                  /**
                  * Get the available container instance.
                  *
                  * @param string $make
                  * @param array $parameters
                  * @return mixed


                  Unfortunately the API documentation doesn't include any of the helper functions, but the current master, 5.2, and 5.3 versions of the file on Github all have the function:



                  • https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/helpers.php#L91

                  • https://github.com/laravel/framework/blob/5.3/src/Illuminate/Foundation/helpers.php#L91

                  • https://github.com/laravel/framework/blob/5.2/src/Illuminate/Foundation/helpers.php#L91






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jun 5 '16 at 23:42

























                  answered Jun 5 '16 at 23:27









                  stratedgestratedge

                  1,864913




                  1,864913























                      0














                      You can inject any service in the handle method:




                      Note that we are able to inject any dependencies we need into the command's handle method.




                      Source: https://laravel.com/docs/5.8/artisan#command-structure






                      share|improve this answer



























                        0














                        You can inject any service in the handle method:




                        Note that we are able to inject any dependencies we need into the command's handle method.




                        Source: https://laravel.com/docs/5.8/artisan#command-structure






                        share|improve this answer

























                          0












                          0








                          0







                          You can inject any service in the handle method:




                          Note that we are able to inject any dependencies we need into the command's handle method.




                          Source: https://laravel.com/docs/5.8/artisan#command-structure






                          share|improve this answer













                          You can inject any service in the handle method:




                          Note that we are able to inject any dependencies we need into the command's handle method.




                          Source: https://laravel.com/docs/5.8/artisan#command-structure







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 7 at 6:25









                          eightyfiveeightyfive

                          2,70822534




                          2,70822534



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37647614%2flaravel-dependency-injection-in-commands%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







                              Popular posts from this blog

                              Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                              2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                              Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme