php - 我正在尝试在启动时编写自定义 Laravel 函数,但出现错误
问题描述
因此,我尝试在 App Service Provider 中编写以下函数,但出现错误:
我的代码是:
public function boot()
{
$homepage = 'https://example.com';
$already_crawled = [];
$crawling = [];
function follow_links($url)
{
global $already_crawled;
global $crawling;
$doc = new \DOMDocument();
$doc->loadHTML(file_get_contents($url));
$linklist = $doc->getElementsByTagName('a');
foreach ($linklist as $link) {
$l = $link->getAttribute("href");
$full_link = 'https://example.com' . $l;
if (!in_array($full_link, $already_crawled)) {
$already_crawled[] = $full_link;
$crawling[] = $full_link;
Log::info($full_link . PHP_EOL);
}
}
array_shift($crawling);
foreach ($crawling as $link) {
follow_links($link);
}
}
follow_links($homepage);
}
因此,使用此代码,我收到如下错误:
in_array() 期望参数 2 为数组,给定 null
我应该怎么做才能没有问题地运行它?
解决方案
你的boot
函数中的变量不是global
,所以你的follow_links
函数的全局变量是一组完全独立的变量。global
在 Laravel 的任何地方,你基本上都不应该有关键字。
由于您的范围问题,$already_crawled
当您第一次尝试将其提供给is_array
. 使用类属性,并$this
访问它们。最重要的是,我删除了奇怪的函数中函数构造:
protected $already_crawled;
protected $crawling;
protected $homepage;
public function boot()
{
$this->homepage = 'https://example.com';
$this->already_crawled = [];
$this->crawling = [];
$this->follow_links($this->homepage);
}
protected function follow_links($url)
{
$doc = new \DOMDocument();
$doc->loadHTML(file_get_contents($url));
$linklist = $doc->getElementsByTagName('a');
foreach ($linklist as $link) {
$l = $link->getAttribute("href");
$full_link = 'https://example.com' . $l;
if (!in_array($full_link, $this->already_crawled)) {
$this->already_crawled[] = $full_link;
$this->crawling[] = $full_link;
Log::info($full_link . PHP_EOL);
}
}
array_shift($this->crawling);
foreach ($this->crawling as $link) {
$this->follow_links($link);
}
}
旁注:您几乎肯定不希望在您的服务提供商中出现这种情况。它将对您的应用所服务的每一个页面浏览进行 HTTPfile_get_contents
调用。它会显着降低您的应用程序的速度。
推荐阅读
- sql - 使用变量作为 UNLOAD SQL 的文件名
- excel - VB.net 我无法明确声明要在项目目录中保存 excel 工作簿
- json - 在 python 和 FourSqaure API 中将 json 文件转换为数据框
- spring - 当应用程序中有多个 @JmsListener 时会发生什么?(在并发方面)
- javascript - 如何将 vuelidate 与对象数组一起使用?
- ios - 问:如何拒绝 Apple Sign In 中隐藏的电子邮件标志?
- excel - 重新安装 Windows 后运行宏
- unity3d - 如果已经检测到图像,如何禁用图像检测
- javascript - 这个人为的例子是否反映了 Reader monad 的目的?
- api - React Native 应用程序似乎无法与 API 通信