Method of Adding Custom Auxiliary Function in Laravel5 Framework
- 2021-10-25 06:17:38
- OfStack
In this paper, an example is given to describe the method of adding custom auxiliary functions to Laravel5 framework. Share it for your reference, as follows:
Laravel contains many very useful helper functions, such as
array_get()
,
array_first()
,
app_path()
And so on, you can see the document http://laravelacademy.org/post/205. html for details. These auxiliary functions provide us with many simple and easy-to-use functions and improve our development efficiency, but what if we want to add custom auxiliary functions? In fact, it is very easy, and it can be done in 4 steps:
1. Create custom helper functions
Here we put the function in app/Support/Helpers/CustomHelper. php:
<?php
if (! function_exists('test_function')) {
function test_function() {
echo " I am 1 Custom helper functions ";
}
}
2. Auxiliary function file loading
Create the file app/Support/Helpers/Helpers. php and load the file containing the custom function:
<?php
$helpers = [
'CustomHelper.php'
];
// Load
foreach ($helpers as $helperFileName) {
include __DIR__ . '/' .$helperFileName;
}
3. Automatically load the Helpers. php file in composer. json
/*composer.json*/
{
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Support/Helpers/helpers.php"
]
}
}
4. Recompile the autoload. php file
Run the following command:
composerdump-autoload
After running, you can call your custom function anywhere, which is as simple as that.
For more readers interested in Laravel related content, please check the topics on this site: "Introduction and Advanced Tutorial of Laravel Framework", "Summary of Excellent Development Framework of php", "Introduction Tutorial of php Object-Oriented Programming", "Introduction Tutorial of php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"
I hope this article is helpful to the PHP programming based on Laravel framework.