首页 > 解决方案 > 我正在尝试在启动时编写自定义 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

我应该怎么做才能没有问题地运行它?

标签: phplaravel

解决方案


你的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调用。它会显着降低您的应用程序的速度。


推荐阅读