首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我试图在启动时编写一个自定义的Laravel函数,但是我得到了错误

我试图在启动时编写一个自定义的Laravel函数,但是我得到了错误
EN

Stack Overflow用户
提问于 2018-11-21 04:24:44
回答 1查看 50关注 0票数 0

因此,我尝试在App Service Provider中编写以下函数,但遇到错误:

我的代码是:

代码语言:javascript
复制
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

我应该怎么做才能运行这个程序而没有问题呢?

EN

回答 1

Stack Overflow用户

发布于 2018-11-21 05:04:59

boot函数中的变量不是global,因此follow_links函数的全局变量是一组完全独立的变量。基本上,在Laravel中的任何地方都不应该有关键字global,永远不应该。

由于您的作用域问题,当您第一次尝试将其提供给is_array时,$already_crawled是未定义的。使用类属性和$this来访问它们。最重要的是,我删除了奇怪的函数中函数结构:

代码语言:javascript
复制
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);
    }
}

附注:几乎可以肯定的是,不希望在您的服务提供商中出现这种情况。它将在你的应用程序为提供服务的每一个页面视图上对进行一个HTTP file_get_contents调用。这将大大降低你的应用程序的速度。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53400978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档