0
你好,我正在學習PHP和我正在用Slim3框架構建一個REST API。我喜歡這個創建路線:Slim3容器的良好做法?
$container['HomeController'] = function() {
return new HomeController();
};
$currentContainer = CurrentContainer::getInstance();
$currentContainer->setContainer($container);
$app->get('/', 'HomeController:index')->setName("index");
我的問題是,我不得不在$容器傳遞給每一個控制器類iv'e創建的,因爲我需要在控制器容器上下文路由等
那麼IM建立一個Singleton容器類是這樣的:
class CurrentContainer
{
private static $instance;
private $container;
private function __construct()
{
}
private function __clone()
{
}
public static function getInstance()
{
if (self::$instance == null) {
self::$instance = new CurrentContainer();
}
return self::$instance;
}
public function setContainer($container)
{
$this->container = $container;
}
/**
* @return mixed
*/
public function getContainer()
{
return $this->container;
}
}
所以現在它可以創建一個 「MainController」 是這樣的:
class Controller
{
/**
* @var mixed
*/
protected $view;
/**
* @var
*/
protected $router;
public function __construct()
{
$container = CurrentContainer::getInstance()->getContainer();
$this->view = $container->view;
$this->router = $container->router;
}
}
現在我所有的控制器都從控制器類擴展... 我的問題是現在...它是一個好主意還是有沒有理由不這樣做呢? 即時感謝每一個輸入
這是更多的RouteAction,而不是控制器,因爲當使用__invoke() – geggleto
時,類不能有多個動作哦,我明白了。我想你想用Facades調用容器。我建議你使用照明/外牆。您可以關注[此鏈接](https://www.sitepoint.com/how-laravel-facades-work-and-how-to-use-them-elsewhere/)。 –