构建简单的Laravel后端应用程序。试图保持控制器整洁,并将所有业务逻辑放入Service中,该服务将使用Model查询数据。
我尝试了一些在此处找到的不同选项(示例)和文档。 同时运行composer dump-autoload和composer更新。 仍然收到服务类不存在的错误。
CarController.php
<?php
namespace App\Http\Controllers;
use App\Services\CarService;
class CarController extends Controller
{
protected $carService;
public function __construct(CarService $carService)
{
$this->carService = $carService;
}
public function getCar()
{
return $carService::getCar();
}
}
?>
CarService.php
<?
namespace App\Services;
class CarService
{
public function getCar()
{
return 'Hello';
}
}
?>
在控制器中调用getCar函数时,出现错误:
<?
namespace App\Services;
class CarService
{
public function getCar()
{
return 'Hello';
}
}
?>
邮递员出现以下错误
{ “ message”:“类App \ Services \ CarService不存在”, “ exception”:“ ReflectionException”, “文件”:“ / home / MyDev / BackEnd / vendor / laravel / framework / src / Illuminate / Container / Container.php”, “行”:826, “跟踪”:[ { “文件”:“ / home / MyDev / BackEnd / vendor / laravel / framework / src / Illuminate / Container / Container.php”, “行”:826, “ function”:“ getClass”, “ class”:“ ReflectionParameter”, “ type”:“->”
(我正在使用Postman调用API来调用控制器。 不知道为什么原始响应会打印出CarService的内容,同时说它不存在...)
谢谢
答案 0 :(得分:1)
除了对$carService
的调用之外,您正在做所有事情,应该访问类实例才能访问它,因此请在控制器中尝试以下操作:
public function getCar()
{
return $this->carService->getCar();
}
如果要以静态方法CarService::getCar()
的形式访问它,则无需在控制器中注入服务,并且需要将函数的签名更改为public static function getCar()
在您的服务课程中。
答案 1 :(得分:0)
哦,伙计,发现了问题。我的服务php标签只是“,但必须是” 添加PHP和类被发现,所有的作品。哦,伙计...