laravel 访问laravel环境和类时如何在命令行上运行php脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23428289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run php script on the command line while accessing laravel environment and classes
提问by WildBill
I have a laravel 3 environment on a web server but I want to run a php script on the command line. I'd like to access the same classes and methods that any php script within the laravel environment (for example a controller, model or view file) accesses.
我在 Web 服务器上有一个 Laravel 3 环境,但我想在命令行上运行一个 php 脚本。我想访问 laravel 环境中的任何 php 脚本(例如控制器、模型或视图文件)访问的相同类和方法。
How can I do that?
我怎样才能做到这一点?
回答by Antonio Carlos Ribeiro
To use the Laravel application in your own script, it needs to load two things from your application directory before starting:
要在您自己的脚本中使用 Laravel 应用程序,它需要在启动之前从您的应用程序目录中加载两件事:
Laravel 3
Laravel 3
This might not be exactly the way, but you should be able to boot it by doing:
这可能不是完全正确的方式,但您应该能够通过执行以下操作来启动它:
define('LARAVEL_START', microtime(true));
require 'paths.php';
require path('sys').'core.php';
Laravel 4
Laravel 4
The Composer autoload script, to autoload all of your classes:
Composer 自动加载脚本,用于自动加载您的所有类:
require __DIR__.'/../bootstrap/autoload.php';
And if you need things from the IoC container, you'll:
如果您需要 IoC 容器中的东西,您将:
$app = require_once __DIR__.'/../bootstrap/start.php';
Then you will be able to do things like:
然后,您将能够执行以下操作:
$post = Post::find(1);
回答by ollieread
I would highly recommend that you migrate your PHP script over to an artisan command. You can find more information here: http://laravel.com/docs/commands
我强烈建议您将 PHP 脚本迁移到 artisan 命令。您可以在此处找到更多信息:http: //laravel.com/docs/commands
This basically gives you access by default, as well as a lot of handy output and argument/option methods to simplify everything.
这基本上为您提供了默认访问权限,以及许多方便的输出和参数/选项方法来简化一切。
As a general rule of thumb, if you're running scripts that have to do something with Laravel, use commands.
作为一般经验法则,如果您运行的脚本必须使用 Laravel 执行某些操作,请使用命令。