简体   繁体   English

在Laravel中,我们应该使用Event来减少控制器依赖性吗?

[英]In Laravel, should we use Event to reduce controller dependency?

Let's say we are to implement a Facebook Like button, in backend a number of things may happen with this simple action. 假设我们要实现一个Facebook Like按钮,在后端,通过此简单操作可能会发生很多事情。 For example: crawl page , extract page data , store page info , associate with user etc... 例如: crawl pageextract page datastore page infoassociate with user等...

After creating modules (libraries + repositories) for each steps, we need to put them together in controller. 在为每个步骤创建模块(库+存储库)之后,我们需要将它们放到控制器中。 Would it be better to create controllers for each module, than injecting all of them within a single controller? 为每个模块创建控制器比将所有模块注入单个控制器会更好吗?

To illustrate in code, is A more maintainable than B ? 为了说明代码, A是否比B更可维护

A: A:

controllers/
  like.php
  crawler.php
  extract.php
  ...

//and in like.php
$page = Event::fire('page.crawler', $url);
...
$result = Event::fire('page.extract', $data);
...

//in crawler.php
use Lib/CrawlInterface;
function __construct (CrawlInterface $crawl)

//in extract.php
use Lib/ExtractInterface;
function __construct (ExtractInterface $extract)

...

B: B:

controllers/
  like.php

//and in like.php
use Lib/CrawlInterface;
use Lib/ExtractInterface;
use ...

function __construct (CrawlInterface $crawl, ExtractInterface $extract, ...)

Obviously this is not a black & white question, but I would like to know whether Event should be used this way, as it seems like a good way for reducing the number of DI on each controller (also prevent controller from going fat.) 显然,这不是一个黑白问题,但我想知道是否应该以这种方式使用Event ,因为这似乎是减少每个控制器上DI数量的好方法(还可以防止控制器变胖)。

Controllers in Laravel are meant to provide endpoints into your webapp with some basic functionality. Laravel中的控制器旨在为您的Web应用程序提供终结点,并提供一些基本功能。 You should not be communicating between two controllers - abstract out your code into separate classes that controllers can simply invoke. 您不应该在两个控制器之间进行通信-将代码抽象到控制器可以简单调用的单独的类中。 This way your controllers stay separated and focused on what their respective routes are meant to do, but can still call the complex domain level functionality you want without mucking up communication. 这样,您的控制器就可以保持分离状态,并专注于各自路由的意图,但仍可以调用所需的复杂域级别功能,而不会影响通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM