gpt4 book ai didi

php - 如何在 Laravel 4 中注入(inject)多个共享相同接口(interface)的类

转载 作者:IT王子 更新时间:2023-10-29 00:12:13 24 4
gpt4 key购买 nike

假设我有一个接口(interface) CrawlerInterface 实现了 PageCrawlerFeedCrawler;如果我们碰巧在 Controller 中需要这两个类,如何通过构造函数注入(inject)来实现?

以前我们使用一个中央ServiceProvider来注册(即App::bind)这样的类,但在大多数情况下我们只有一个接口(interface)的实现,所以说我们还没有遇到问题。

PS:我也想知道这个问题是否建议我们应该拆分 Controller 。


更新:

感谢您的评论和回复,解释一下,该接口(interface)只有一个公共(public)方法:crawl($uri),并且页面/提要爬虫都将其实现为给定的资源标识符, 返回资源。


我的后续问题:

假设我们处于一个计算器场景中,其中加法、减法和乘法共享相同的接口(interface)Operation,它只有一个公共(public)方法run ,在某些时候我们仍然会遇到这个问题对吗?我们通常如何使用 ServiceProvider 处理此类情况?

最佳答案

如果每个爬虫存在的原因不同,您可以为您的实例使用任意名称,例如:

App::bind('crawler.allArticles', 'PageCrawler');
App::bind('crawler.latestArticles', 'FeedCrawler');

对于 Controller :

App::bind('CrawlerController', function($app) {
return new CrawlerController(
App::make('crawler.allArticles'),
App::make('crawler.latestArticles')
);
});

然后您的 Controller 代码将以不同方式使用每个爬虫:

public function showLatestArticlesAction()
$latestArticles = $this->latestArticlesCrawler->crawl();
// ...
}

public function showAllArticlesAction()
$allArticles = $this->allArticlesCrawler->crawl();
// ...
}

如果您只有一个爬虫列表,其中每个爬虫都用于相同的事情,您可能想要执行如下操作:

App::bind('crawlers', function($app) {
return [
App::make('PageCrawler'),
App::make('FeedCrawler'),
];
});

在您的 Controller 中,您将通过如下配置获得“爬虫”列表:

App::bind('CrawlerController', function($app) {
return new CrawlerController(App::make('crawlers'));
});

你的 Controller 代码可能是这样的:

public function showArticlesAction()
$allArticles = array();
foreach ($this->crawlers as $crawler) {
$allArticles = array_merge($allArticles, $this->crawler->crawl());
}
// ...
}

关于php - 如何在 Laravel 4 中注入(inject)多个共享相同接口(interface)的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19365138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com