Home >Backend Development >PHP Tutorial >3 ways to use your own class library in Laravel_PHP tutorial
This article mainly introduces 3 ways to use self-written class libraries in Laravel. This article explains how to add direct There are three ways to instantiate classes, add directly callable functions, and add slightly more complex class libraries. Friends in need can refer to the following
Although Composer allows us to reuse many existing libraries (such as those in packagist.org), we may still use some packages or libraries that are not compatible with composer. In addition, in a certain project, we may also create a certain class library, and we may not intend to make it into a composer package. At this time we can use our own unique class library in the following ways.
Add classes that can be instantiated directly
Some classes that need to be used directly in the project can be added to Laravel in the following ways
1. Create the class library file app/libraries/class/myClass.php
2. Write file content
The code is as follows:
}
}
?>
Add class import path in app/start/globals.php
The code is as follows:
app_path().'/commands',
app_path().'/controllers',
app_path().'/models',
app_path().'/database/seeds',
app_path().'/libaries/class', // Add
));
?>
Add the autoload directory in composer.json
The code is as follows:
1. Execute composer dump-autoload to create import mapping
2. Use the class you imported to directly call Message::display()
This method is also a way to add a queue class. Many people don’t know where the queue processing class should be placed in Laravel. In fact, follow the above method to create a queues directory in the app directory, and then allow it to be instantiated directly. That’s it
Add functions that can be called directly
Some people like to use v() instead of var_dump(), and it is very easy to do this in Laravel
1. Create a function file app/libraries/function/helper.php
2. Write file content
The code is as follows:
Add the file to composer’s automatic import list
The code is as follows:
Or display require this file in the project. Open app/start/global.php and add:
at the endThe code is as follows:
The code is as follows:
Use function v('hello world');
directly in the projectAdd a slightly more complex class library
Sometimes a class library is more than just a file, so the following method is more suitable for class libraries with multiple files and multiple structures.
Create a psr0 or psr4 standard directory structure.
The code is as follows:
Modify autoload in composer
The code is as follows:
Summary
Although Laravel does not force which method is best, there are certain standards that can make the project structure clear and save a lot of communication costs when multiple people cooperate in development.