有必要在基础构造函数中连接服务,以便该服务在继承基础的所有控制器中工作,但此构造函数不起作用。
给出错误消息:
Target [App\Services\GeneralAppLayerInterface] is not instantiable while building [App\Http\Site\Controllers\HomeController].
use App\Services\GeneralAppLayerInterface;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController {
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public $general;
public function __construct(
GeneralAppLayerInterface $general
) {
$this->general = $general;
}
}
通用应用层接口
interface GeneralAppLayerInterface
{
/**
* Returns an array with resources.
*
* @param array $params
*
* @return array
*/
public function getData(array $params = null);
}
一般事务
class GeneralService implements GeneralAppLayerInterface {
public $path;
private $settings;
private $menu;
public function __construct() {
}
public function getData(array $params = null){
$data = some data;
return [
'data' => $data
];
}
应用服务提供者
use App\Http\Site\Controllers\Controller;
use App\Services\GeneralAppLayerInterface;
use App\Services\Site\GeneralService;
use Illuminate\Support\ServiceProvider;
use DB;
class AppServiceProvider extends ServiceProvider {
/**
* Register any application services.
*
* @GeneralService - frontend service
* @return void
*/
public function register() {
$this->app->when(Controller::class)
->needs(GeneralAppLayerInterface::class)
->give(function ($app) {
return $app->make(GeneralService::class);
});
}
家庭控制器
use App\Http\Site\Controllers\Controller;
class HomeController extends Controller {
public function index() {
$data = $this->general->getData();
dump($data);
如何解决?
应该管用