Generate services in Laravel with the artisan command

Overview

Logo

Laravel Service Generator

Quickly generate services for your projects!



Table of Contents

  1. Features
  2. Installation
  3. Usage
  4. The service pattern
  5. More generator packages
  6. Contributing
  7. License

Features

This package adds the php artisan make:service {name} command. The command generates an empty service class in app\Services to get started. I made this mainly for own use because I like to be able to generate recurring files from the command line to keep my workflow consistent.

Installation

Install the package with composer.

composer require timwassenburg/laravel-service-generator

Usage

After installation the php artisan make:service {name} will be available in the list of artisan commands.

Generate Service

To generate a new service use the following artisan command.

php artisan make:service UserService

Generate a service for a model

Add a --service or -S param to generate a service for the model.

php artisan make:model Post --service

Use the -a or --all param to generate a service, migration, seeder, factory, policy, and resource controller for the model.

php artisan make:model Post --all

Generate a service for a controller

Add a --service or -S param to generate a service for the controller.

php artisan make:controller PostController --service

The service pattern

When to use the service pattern

A common question is: where do I put my business logic? You want to keep your models thin and your controller functions skinny. There are multiple ways to archive this, extracting your business logic to the service layer is a common method. By encapsulating your business logic in a service class you are able to re-use the logic for example in your controllers, commands, jobs and middelware.

How to use services

Once you have made a service it is time to add your business logic. We will discus how to use a service via static methods, dependency injection and how to use it with interfaces and repositories.

Static methods

a common way to use a service is to call it's methods statically. It is similar to helper functions. Let's say we have a PostService with a method to get a post based on a slug.

namespace App\Services;

use App\Models\Post;

class PostService
{
    // Declare the function as static
    public static function getPostBySlug(string $slug): Post
    {
        return Post::with('tags')
            ->where('slug', $slug)
            ->get();
    }
}

Next you can include the service class for example your controller and call the getPostBySlug method statically.

namespace App\Http\Controllers;

// Include the service
use App\Services\PostService;

class PostController extends Controller
{
    public function show(string $slug)
    {
        // Call the method statically from the service class
        $post = PostService::getPostBySlug($slug);
        
        return view('posts.show', compact('post'));
    }
}#

The getPostBySlug method is in this example a very simple function but as you can see it keeps you controller skinny and and your business logic seperated. Keep in mind that static classes and methods are stateless. The class won't save any data in itself.

Dependency Injection

Another popular method is to use services with dependency injection. With dependency injection you can write loosely coupled code. When done right this will improve the flexibility and maintainability of your code.

The PostService we used as example before will remain almost the same except we don't declare the functions inside the class as static anymore.

namespace App\Services;

use App\Models\Post;

class PostService
{
    public function getPostBySlug(string $slug): Post
    {
        return Post::with('tags')
            ->where('slug', $slug)
            ->get();
    }
}

Next we inject the service into the constructor of the class where we want to use it. Inside the constructor we assign the object to the $postService class property. Now the $postService property will be callable in all functions within the class with $this->postService. While typing your IDE will already typehint the functions in your PostService class, in this case only ->getPostBySlug($slug).

namespace App\Http\Controllers;

// Include the service
use App\Services\PostService;

class PostController extends Controller
{
    // Declare the property
    protected $postService;

    // Inject the service into the constructor
    public function __construct(PostService $postService)
    {
        // Assign the service instance to the class property
        $this->postService = $postService;
    }

    public function show($slug)
    {
        // Call the method you need from the service via the class property
        $post = $this->postService->getPostBySlug($slug);
        
        return view('posts.show', compact('post'));
    }
}

More generator packages

Looking for more ways to speed up your workflow? Make sure to check out these packages.

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

The MIT License (MIT). Please see License File for more information.

You might also like...
Dispatch Laravel jobs via Artisan
Dispatch Laravel jobs via Artisan

This package can register jobs as Artisan commands. All you need to do is let your job implement the empty ArtisanDispatchable interface.

A Laravel Artisan SQL Interactive Interface
A Laravel Artisan SQL Interactive Interface

sqli A Laravel 4 & 5 Artisan SQL Interactive Interface, plus a handful of Artisan commands to execute SQL queries. sqli It's like tinker for SQL, just

Package for Laravel that gives artisan commands to setup and edit environment files.
Package for Laravel that gives artisan commands to setup and edit environment files.

Setup and work with .env files in Laravel from the command line NOTE: This doesn't work with Laravel 5 since .env files were changed. This is for Lara

This package is to add a web interface for Laravel 5 and earlier Artisan.
This package is to add a web interface for Laravel 5 and earlier Artisan.

Nice Artisan This package is to add a web interface for Laravel 5 and earlier Artisan. Installation Add Nice Artisan to your composer.json file : For

A nice GUI for Laravel Artisan, ready out of the box, configurable and handy for non-CLI experienced developers.

Artisan UI A nice GUI for Laravel Artisan, ready out of the box, configurable and handy for non-CLI experienced developers. Supported commands must be

A bookmarkable, searchable cheatsheet for all of Laravel's default Artisan commands.

artisan.page A bookmarkable, searchable cheatsheet for all of Laravel's default Artisan commands. Generation The generation of the manifest files is d

Laravel API architecture builder based on artisan commands.

πŸ§‘β€πŸ”¬ API-Formula Laravel API architecture builder based on artisan commands. This package provides a nice and fluent way to generate combined control

This Laravel Nova tool lets you run artisan and bash commands directly from Nova 4 or higher.
This Laravel Nova tool lets you run artisan and bash commands directly from Nova 4 or higher.

Laravel Nova tool for running Artisan & Shell commands. This Nova tool lets you run artisan and bash commands directly from nova. This is an extended

Execute Laravel Artisan commands via REST APIs and HTTP requests safely.

Artisan Api There might be some times you wanted to execute an Artisan command, but you did not have access to shell or SSH. Here we brought REST API

Releases(v1.0.2)
Owner
Tim Wassenburg
Sr. Full-stack Developer | Contact me for availability.
Tim Wassenburg
πŸ“ Artisan Menu - Use Artisan via an elegant console GUI

?? Artisan Menu Use Artisan via an elegant console GUI Features Run built-in and custom Artisan commands from a console GUI Prompts to enter required

Jordan Hall 149 Dec 29, 2022
πŸ“ Artisan Menu - Use Artisan via an elegant console GUI

?? Artisan Menu Use Artisan via an elegant console GUI Features Run built-in and custom Artisan commands from a console GUI Prompts to enter required

Jordan Hall 148 Nov 29, 2022
πŸ“¦ Adds Laravel Packages Support to Lumen and Vendor Publish Artisan Command.

Laravel Package Support for Lumen: Makes Lumen compatible with Laravel Packages. You can use any Laravel Packages in Lumen by installing Larasupport Package.

Irfaq Syed 127 Dec 17, 2022
Create Laravel views (blade template) using 'php artisan' command-line interface

About LaraBit Have you ever wonder to create Laravel views (Blade Templates) using the same type of artisan commands that you usually use to create ne

Ragib MRB 5 Oct 15, 2021
An artisan command for using multiple environment configurations in Laravel 5

Laravel 5 env An artisan command for managing multiple .env of your Laravel 5 app. Installation Copy EnvCommand.php to app/Console/Commands/ of your L

Tommy Ku 18 Nov 29, 2022
This package provides you with a simplistic `php artisan make:user` command

Laracademy Generators Laracademy make:user Command - provides you with a simplistic artisan command to generate users from the console. Author(s): Lar

Laracademy 18 Jan 19, 2019
Easily generate URLs to Minecraft avatars with the ability to switch between services

Minecraft Avatar URLs This library provides PHP utilities to generate URLs to Minecraft Avatars in different formats with the ability to easily change

Gigadrive UG 3 Aug 11, 2022
Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Jameson Lopp 28 Dec 19, 2022
Generate trends for your models. Easily generate charts or reports.

Laravel Trend Generate trends for your models. Easily generate charts or reports. Support us Like our work? You can support us by purchasing one of ou

Flowframe 139 Dec 27, 2022
πŸ‘€ Manage your views in Laravel projects through artisan

Artisan View This package adds a handful of view-related commands to Artisan in your Laravel project. Generate blade files that extend other views, sc

Sven Luijten 842 Dec 29, 2022