search
HomePHP FrameworkLaravelIntroducing Laravel's custom Make command to generate Service class

The following tutorial column from laravel will introduce you to the Laravel custom Make command to generate the Service class. I hope it will be helpful to friends in need!

Environment Description

The environment I use is: Laravel Framework 8.40.0.

C:\www\wwwroot\laravel8>php artisan --version
Laravel Framework 8.40.0

1. Making command files

For tutorials related to early knowledge, please refer to my other blog Laravel custom Make command to generate target classes.

  1. Run the following command

     php artisan make:command MakeService

    Generate the Console/Commands/MakeService.php command file.

  2. Modify the inherited class
    Modify the inherited class to GeneratorCommand, the namespace of this class is Illuminate\Console\GeneratorCommand.
    Delete the instantiation method, handle function
    implement a method getStub.

  3. Set the name attribute.
    Modify the $signature attribute to the name attribute, and set the command:

     protected $name = 'make:service';
  4. Set the type attribute value
    typeType setting, what we generate is service, so the attribute we set is Service.

     protected $type = 'Service';

    The type type is defined by yourself. It has no special meaning and does not need to be set.

    The type attribute value only gives you a friendly prompt when creating an error, as shown below:

     C:\www\wwwroot\laravel8>php artisan make:service TestService
     already exists!
    
     C:\www\wwwroot\laravel8>php artisan make:service TestService
     Service already exists!

    The first one is not settype The effect of attributes, the second one is the effect of setting the type attribute.

    The officially used types are: Controller, Middleware, Cast, Channel...

    Modify other attributes according to your own needs

  5. Set the location and command space of Stub
    The location of Stub is in the root directory Stubs/service.stub.
    The namespace is in Services under the app directory.

The example code is as follows:

<?php namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
class MakeService extends GeneratorCommand{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = &#39;make:service&#39;;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = &#39;生成service对象类&#39;;

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = &#39;Service&#39;;

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        // Implement getStub() method.
        return $this->laravel->basePath('/stubs/service.stub');
    }

    /**
     * Get the default namespace for the class.
     *
     * @param  string  $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Services';
    }}

2. Making Stub files

My service file currently does not need to be inherited or relied on What category. So, it's relatively simple. If you have special needs, you can extend the operation.

The example code is as follows:

<?phpnamespace  DummyNamespace;class DummyClass{
    //}

DummyClass and DummyNamespace will be automatically changed inside the inherited GeneratorCommand class Replace with the automatically generated class name and set namespace.

It is recommended that you use the editor's syntax prompts to get a more friendly prompt effect.
In addition, you can also use Larave's built-in {{ class }} and {{ namespace }} writing methods.

3. Test Service generation

Execute the following command

php artisan make:service IndexService

It can be generated successfully

C:\www\wwwroot\laravel8>php artisan make:service IndexService
Service created successfully.

The directory of the generated file is app/Services/IndexService.php, the generated file is as follows:

<?php namespace App\Services;
class IndexService{
    //}

Related recommendations: The latest five Laravel video tutorials

The above is the detailed content of Introducing Laravel's custom Make command to generate Service class. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Beyond the Zoom Call: Creative Strategies for Connecting Distributed TeamsBeyond the Zoom Call: Creative Strategies for Connecting Distributed TeamsApr 26, 2025 am 12:24 AM

ToenhanceengagementandcohesionamongdistributedteamsbeyondZoom,implementthesestrategies:1)Organizevirtualcoffeebreaksforinformalchats,2)UseasynchronoustoolslikeSlackfornon-workdiscussions,3)Introducegamificationwithteamgamesorchallenges,and4)Encourage

What are the breaking changes in the latest Laravel version?What are the breaking changes in the latest Laravel version?Apr 26, 2025 am 12:23 AM

Laravel10introducesseveralbreakingchanges:1)ItrequiresPHP8.1orhigher,2)TheRouteServiceProvidernowusesabootmethodforloadingroutes,3)ThewithTimestamps()methodonEloquentrelationshipsisdeprecated,and4)TheRequestclassnowpreferstherules()methodforvalidatio

The Productivity Paradox: Maintaining Focus and Motivation in Remote SettingsThe Productivity Paradox: Maintaining Focus and Motivation in Remote SettingsApr 26, 2025 am 12:17 AM

Tomaintainfocusandmotivationinremotework,createastructuredenvironment,managedigitaldistractions,fostermotivationthroughsocialinteractionsandgoalsetting,maintainwork-lifebalance,anduseappropriatetechnology.1)Setupadedicatedworkspaceandsticktoaroutine.

Building Trust from Afar: Fostering Collaboration in Distributed EnvironmentsBuilding Trust from Afar: Fostering Collaboration in Distributed EnvironmentsApr 26, 2025 am 12:13 AM

Tofostercollaborationandtrustinremoteteams,implementthesestrategies:1)Establishregular,structuredcommunicationwithpersonalcheck-ins,2)Usecollaborativetoolsfortransparency,3)Recognizeandcelebrateachievements,and4)Fosteracultureoftrustandadaptability.

What are the key features of the latest Laravel version?What are the key features of the latest Laravel version?Apr 26, 2025 am 12:01 AM

Laravel's latest version of the main features include: 1. LaravelOctane improves application performance, 2. Improved model factory support relationships and state definitions, 3. Enhanced Artisan commands, 4. Improved error handling, 5. New Eloquent accessors and modifiers. These features significantly improve development efficiency and application performance, but need to be used with caution to avoid potential problems.

The Illusion of Inclusion: Addressing Isolation and Loneliness in Remote WorkThe Illusion of Inclusion: Addressing Isolation and Loneliness in Remote WorkApr 25, 2025 am 12:28 AM

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravel for Full-Stack Development: A Comprehensive GuideLaravel for Full-Stack Development: A Comprehensive GuideApr 25, 2025 am 12:27 AM

Laravelispopularforfull-stackdevelopmentbecauseitoffersaseamlessblendofbackendpowerandfrontendflexibility.1)Itsbackendcapabilities,likeEloquentORM,simplifydatabaseinteractions.2)TheBladetemplatingengineallowsforclean,dynamicHTMLtemplates.3)LaravelMix

Video Conferencing Showdown: Choosing the Right Platform for Remote MeetingsVideo Conferencing Showdown: Choosing the Right Platform for Remote MeetingsApr 25, 2025 am 12:26 AM

Key factors in choosing a video conferencing platform include user interface, security, and functionality. 1) The user interface should be intuitive, such as Zoom. 2) Security needs to be paid attention to, and Microsoft Teams provides end-to-end encryption. 3) Functions need to match requirements, GoogleMeet is suitable for short meetings, and CiscoWebex provides advanced collaboration tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.