Laravel 5.1 - 如何在全局函数文件中使用模型

Laravel 5.1 - How to use Model in Global function file

我为我的所有全局函数创建了一个 common.php。当我 运行 我的第一个函数 {{Common::test()}}

它工作正常但我不能在其中使用模型。

namespace App\library;
{
    class Common {

            public static function test()
            {
                echo "Yes";
                return "This comes from Common File";
            }
            public static function getCmsBlocks()
            {
                $model = Modelname::all();
                if($model){
                    echo "asdad";
                }else
                {
                    echo "sadasd";
                }
            }

    }
}

当我 运行 {{Common::getCmsBlocks()}}

时我没有得到我的输出

如果您的模型位于与 App\library 不同的命名空间中,您需要在模型 class 名称前加上其命名空间前缀,否则 PHP 将尝试加载 App\library\Modelname 这可能不是您需要的。

替换

$model = Modelname::all();

$model = \Your\Model\Namespace\Modelname::all();

如果您在声明的命名空间中的多个位置使用 Modelname class,您可以 import/alias 使用 use 语句,以便您可以在代码中通过 classname 引用 class:

namespace App\library;
use Your\Model\Namespace\Modelname;
{
  class Common {
    public static function getCmsBlocks()
    {
      $model = Modelname::all(); //this will work now
    }
  }
}

无法将全局 use 定义为文件中所有名称空间的总线,因为 use 始终指的是名称空间宣布。

如上所述,答案是完美的,但如果您不想每次都在每个文件的开头包含名称空间,则只需添加一些内容

使用这个:

\App\ModelName::all();
\App\ModelName1::update(item);
\App\ModelName2::find(1);

像上面那样给出路径,就不需要每次都使用命名空间了。

注意:以上是App目录下的模型路径。因此,如果您将它们放在不同的地方,请相应地进行更改。