我刚刚阅读这篇文章,以创建一个能够从任何控制器访问的全局函数.但我不明白它是如何工作的.
我想让任何控制器都可以访问变量'services'.所以,我制作General.php并将其放在app/Http中.这是代码.
<?php
class General {
public function getServices() {
$services = "SELECT * FROM products";
return $services;
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中我包括它
<?php
namespace App\Http\Controllers;
use App\Http\General;
use Illuminate\Http\Request;
class HomeController extends Controller {
public function index() {
$title = 'Our services';
$services = General::getServices();
return view('welcome', compact('title','services'));
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到了错误Class 'App\Http\General' not found.然后我将如何能够帮助任何人都会感激不尽.
首先app在.php文件中的目录中创建所需的函数
helpers.php
if (!function_exists('getServices')) {
public function getServices() {
return DB::table('services')->get();
}
}
Run Code Online (Sandbox Code Playgroud)
并将此文件包含在composer.json内部autoload/files数组中
composer.json
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers.php"
]
},
Run Code Online (Sandbox Code Playgroud)
然后update the composer,现在您可以直接在整个项目中使用创建的函数,因为当应用程序获得引导时文件会自动加载
$result = getServices();
Run Code Online (Sandbox Code Playgroud)