The following tutorial column from Laravel will introduce how to use PHP traits to implement a simple Facade. I hope it will be helpful to everyone!
##Brief Description
Facade can effectively help me realize the staticization of the method.
Laravel Most extension packages use
Facade. [Recommended:
laravel video tutorial]The following simple
Facade mainly uses PHP's features
trait, magic method
__callStatic, Reflection Class
ReflectionClass.
Usage scenarios
Most background systems will have operations similar to this:<?php $user = User::find($id);if (!$user) { throw new \Expection("资源不存在");}There seems to be no problem, But there will also be the following:
$article = Article::find($id);if (!$article) { throw new \Expection("资源不存在");}$article->delete();This way of writing is very inelegant.
Code
1. First we should have a Service
<?phpnamespace App\Services;use App\Traits\ModeServiceTrait;class ModelService extends BaseService{ use ModeServiceTrait;}
2. Create a new Trait
trait exists for multiple inheritance. You can go to the PHP official website to read the documentation.<?php namespace App\Traits; use \ReflectionClass; use \Exception;use \ReflectionException; use Illuminate\Database\Eloquent\Model; use App\Exceptions\ResourceException; /** * @method static Model find(string $className, int $id, callable $callback = null) * * @see Model * @package App\Services */trait ModeServiceTrait{ /** * 回调方法 * * @param Model|null $model * @param string $method * @return Model * @throws ResourceException */ public static function callback(Model|null $model, string $method): Model { switch ($method) { case 'first': case 'find': if (!$model) { throw new ResourceException("资源不存在"); } break; default: break; } return $model; } /** * 调用不存在的方法时触发 * * @param $method * @param $args * @return false|mixed * @throws ReflectionException * @throws ResourceException * @throws Exception */ public static function __callStatic($method, $args) { $className = $args[0]; $arg = $args[1]; // 判断模型类是否存在 if (!class_exists($className)) { throw new Exception("The class {$className} could not be found. from:" . __CLASS__); } // 利用反射实例化其类 $reflection = new ReflectionClass($className); $instance = $reflection->newInstanceArgs(); // 调用该不存在的方法 $model = call_user_func_array([$instance, $method], [$arg]); // 如果存在复杂操作交给 callback return isset($args[2]) ? $args[2]($model) : self::callback($model, $method); }}First we focus on the
__callStatic magic method. This method is triggered when a non-existing static method is called. A magic method similar to his is
__call. This is to use
__callStatic to achieve the effect of
Facade.
__callStatic There are two callback parameters
$method is a
called method that does not exist ,
$args It is the parameter (array form) passed in the
$method method.
trait is completed.
Use
We create a newcommand
$ php artisan make:command TestCommandWrite the following content
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use App\Services\ModelService; use App\Models\Article\Article; class TestCommand extends Command{ /** * The name and signature of the console command. * * @var string */ protected $signature = 'test:test'; /** * The console command description. * * @var string */ protected $description = 'a test'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. */ public function handle() { $article = ModelService::find(Article::class, 1); $article = ModelService::find(Article::class, 1, function ($model) { return $model->load('author'); }); }}The
Article model needs to be created by yourself.
Next you can see the effect:
$ php artisan test:test
Conclusion
In this way we abandon the use ofabstract Abstract class to achieve the same effect as
Facade. Code reuse is also achieved.
Using the program in this way will take a lot more steps, but compared to elegance, performance doesn't matter.
The above is the detailed content of Implementing a simple Laravel Facade using PHP features traits. For more information, please follow other related articles on the PHP Chinese website!

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.

Choosing Laravel or Python depends on the project requirements: 1) If the project is mainly web development and needs to quickly build complex applications, choose Laravel; 2) If data science, machine learning or more flexibility is involved, choose Python.

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Laravel is a modern PHP framework that provides a powerful tool set, simplifies development processes and improves maintainability and scalability of code. 1) EloquentORM simplifies database operations; 2) Blade template engine makes front-end development intuitive; 3) Artisan command line tools improve development efficiency; 4) Performance optimization includes using EagerLoading, caching mechanism, following MVC architecture, queue processing and writing test cases.

Laravel's MVC architecture improves the structure and maintainability of the code through models, views, and controllers for separation of data logic, presentation and business processing. 1) The model processes data, 2) The view is responsible for display, 3) The controller processes user input and business logic. This architecture allows developers to focus on business logic and avoid falling into the quagmire of code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft