3 回答
TA贡献1820条经验 获得超2个赞
不在其他控制器中重用控制器更干净。更好的方法是将您要从控制器重用的逻辑提取到一个单独的服务中,然后您可以从两个控制器调用该服务。
例子:
class HomeController extends Controller
{
/**
* @var NewsService
*/
private $newsService;
/**
* @var ArticleService
*/
private $articleService;
public function __construct(NewsService $newsService, ArticleService $articleService)
{
$this->newsService = $newsService;
$this->articleService = $articleService;
}
public function index()
{
$news = $this->newsService->getNews();
$articles = $this->articleService->getArticles();
return view('template',['news'=>$news,'articles'=>$articles]);
}
}
class NewsController extends Controller
{
/**
* @var NewsService
*/
private $newsService;
public function __construct(NewsService $newsService)
{
$this->newsService = $newsService;
}
public function index()
{
$news = $this->newsService->getNews();
return view('template',['news'=>$news]);
}
}
class ArticleController extends Controller
{
/**
* @var ArticleService
*/
private $articleService;
public function __construct(ArticleService $articleService)
{
$this->articleService = $articleService;
}
public function index()
{
$articles = $this->articleService->getArticles();
return view('template',['articles'=>$articles]);
}
}
TA贡献1829条经验 获得超6个赞
我同意@ptrTon 的观点,我建议采用 Repository 模式。根据您的应用程序大小,这可能需要一些工作,但它绝对比在另一个控制器内实例化控制器更干净。
基本上,使用这种方法,您不会直接操作模型,而是使用一个对象,该对象实际上是一个额外的层。这样做的主要优点是您可以提取通用操作并从任何地方执行它们,而不是在控制器内部,而是在对象内部,唯一的职责是管理模型上的操作,进一步分离应用程序组件的职责。使用 Laravel,您还可以添加自定义路由解析逻辑,该逻辑将使用 IoC 容器将这些存储库注入您的控制器。
如果您想更进一步,您可以创建存储库,使其表现为包装模型并扩展其功能(PHP 的魔法方法是您的朋友)。在单个答案中提供完整示例可能很复杂,但我将在下面链接一些有趣的资源。
Laravel 的显式模型绑定(参见“自定义解析逻辑”部分)
- 3 回答
- 0 关注
- 141 浏览
添加回答
举报