注册自定义命令

最后更新于:2022-04-01 15:13:48

# 注册一个 Artisan 命令 一旦你的自定义命令撰写完成后,你需要将它注册于 Artisan 它才能被使用。这通常位于 `app/Console/Kernel.php` 这个文件中。在此文件的 `commands` 属性,你会找到一份命令的清单。若要注册你的自定义命令,很简单的你只要将它加入清单中。当 Artisan 启动时,被列于此属性中的所有命令都将被 [服务容器](http://www.golaravel.com/laravel/docs/5.0/container) 解析,并且被注册于 Artisan 。
';

建立自定义命令

最后更新于:2022-04-01 15:13:46

# 自动创建类(Class) 要创建一个新的自定义命令,您可以使用 make:console 这个 Artisan 命令,这将会自动产生一个 Command stub 协助您开始创建您的自定义命令: ## 自动创建一个新的命令类 ~~~ php artisan make:console FooCommand ~~~ 上面的命令将会协助你自动创建一个类,并保存为文件 `app/Console/FooCommand.php`。 在创建自定义命令时,加上 `--command` 这个选项,将可以指定之后在终端机使用此自定义命令时,所要输入的自定义命令名称: ~~~ php artisan make:console AssignUsers --command=users:assign ~~~ # 撰写自定义命令 一旦你的自定义命令被创建后,你需要填写自定义命令的 `名称(name)` 与 `描述(description)`,您所填写的内容将会被显示在 Artisan 的 `list` 画面中。 当您的自定义命令被执行时,将会调用 `fire` 方法,您可以在此为自定义命令加入任何的逻辑判断。 # 参数与选项 你可以通过 `getArguments` 与 `getOptions` 为自定义命令自行定义任何需要的参数与选项。这两个方法都会返回一组命令数组,并由选项数组的清单所组成。 当定义 `arguments` 时,该数组值的定义分别如下: ~~~ [$name, $mode, $description, $defaultValue] ~~~ 参数 mode 可以是下列其中一项: `InputArgument::REQUIRED` 或 `InputArgument::OPTIONAL`。 当定义 `options` 时,该数组值的定义分别如下: ~~~ [$name, $shortcut, $mode, $description, $defaultValue] ~~~ 对选项而言,参数 `mode` 可以是下列其中一项:`InputOption::VALUE_REQUIRED`, `InputOption::VALUE_OPTIONAL`, `InputOption::VALUE_IS_ARRAY`, `InputOption::VALUE_NONE`。 模式为 `VALUE_IS_ARRAY` 表示调用命令时可以多次使用此选项来传入多个值: ~~~ InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY ~~~ 这个命令将允许: ~~~ php artisan foo --option=bar --option=baz ~~~ 模式为 `VALUE_NONE` 则表示将此选项纯粹作为一种有或无的「开关」使用: ~~~ php artisan foo --option ~~~ # 取得输入值(参数与选项) 当您的自定义命令执行时,您需要让您的应用程序可以访问到这些参数和选项的值,要做到这一点,您可以使用 `argument` 和 `option` 方法: ## 取得自定义命令被输入的参数 ~~~ $value = $this->argument('name'); ~~~ ## 取得自定义命令被输入的所有参数 ~~~ $arguments = $this->argument(); ~~~ ## 取得自定义命令被输入的选项 ~~~ $value = $this->option('name'); ~~~ ## 取得自定义命令被输入的所有选项 ~~~ $options = $this->option(); ~~~ # 产生输出 想要显示信息到终端屏幕上,您可以使用 `info`、`comment`、`question` 和 `error` 方法。每一种方法将会依据它所代表的目的,分别对应一种适当的 ANSI 颜色。 ## 显示一般消息到终端屏幕 ~~~ $this->info('Display this on the screen'); ~~~ ## 显示错误消息到终端屏幕 ~~~ $this->error('Something went wrong!'); ~~~ # 询问式输入 您也可以使用 `ask` 和 `confirm` 方法来提示用户进行输入: ## 提示用户进行输入 ~~~ $name = $this->ask('What is your name?'); ~~~ 提示用户进行加密输入 ~~~ $password = $this->secret('What is the password?'); ~~~ ## 提示用户进行确认 ~~~ if ($this->confirm('Do you wish to continue? [yes|no]')) { // } ~~~ 您也可以指定一个默认值给 `confirm` 方法,可以是 `true` 或 `false`: ~~~ $this->confirm($question, true); ~~~ # 调用其它命令 有时候您可能希望在您的命令内部调用其它命令,此时您可以使用 `call` 方法: ~~~ $this->call('command:name', ['argument' => 'foo', '--option' => 'bar']); ~~~
';

开发

最后更新于:2022-04-01 15:13:43

# 简介 除了 Artisan 本身提供的命令之外,您也可以为您的应用程序建立属于你自己的命令。你可以将自定义命令存放在 `app/Console/commands` 目录底下;然而,您也可以任意选择存放位置,只要您的命令能够被 `composer.json` 自动加载。
';

定时调用 Artisan 命令

最后更新于:2022-04-01 15:13:41

过去,开发者会对每个他们想要调用的命令行指令建立 Cron 对象。然而,这很令人头痛。你的命令行指令调用不再包含在版本控制里面,并且你必须 SSH 进入你的服务器以添加 Cron 对象。让我们来让生活变得更轻松。Laravel 命令调用器允许你顺畅地且语义化地定义命令调用在 Laravel 里面,而且你的服务器只需要一个 Cron 对象。 你的命令调用保存在 `app/Console/Kernel.php` 文件。你会在这个类里看到一个 `schedule` 方法。为了帮助您开始,方法里面包含一个简单的例子。你可以依照你需要的自由地添加任何数量的预定工作到 `Schedule` 对象。你只需要添加这个 Cron 对象到服务器: ~~~ * * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1 ~~~ 这个 Cron 将会每分钟调用 Laravel 命令调用器。接着,Laravel 评估你的预定工作并在时间到时执行工作。这不能再更简单了! ## 更多调用的例子 让我们来多看几个调用的例子: ### 调用闭包 ~~~ $schedule->call(function() { // 执行一些任务... })->hourly(); ~~~ ### 调用终端机命令 ~~~ $schedule->exec('composer self-update')->daily(); ~~~ ### 自己配置 Cron 表达式 ~~~ $schedule->command('foo')->cron('* * * * *'); ~~~ ### 频繁的工作 ~~~ $schedule->command('foo')->everyFiveMinutes(); $schedule->command('foo')->everyTenMinutes(); $schedule->command('foo')->everyThirtyMinutes(); ~~~ ### 每天一次的工作 ~~~ $schedule->command('foo')->daily(); ~~~ ### 每天一次在特定时间 (24 小时制) 的工作 ~~~ $schedule->command('foo')->dailyAt('15:00'); ~~~ ### 每天两次的工作 ~~~ $schedule->command('foo')->twiceDaily(); ~~~ ### 每个工作日执行的工作 ~~~ $schedule->command('foo')->weekdays(); ~~~ ### 每周一次的工作 ~~~ $schedule->command('foo')->weekly(); // 调用每周一次在特定的日子 (0-6) 和时间的工作... $schedule->command('foo')->weeklyOn(1, '8:00'); ~~~ ### 每月一次的工作 ~~~ $schedule->command('foo')->monthly(); ~~~ ### 特定日期的工作 ~~~ $schedule->command('foo')->mondays(); $schedule->command('foo')->tuesdays(); $schedule->command('foo')->wednesdays(); $schedule->command('foo')->thursdays(); $schedule->command('foo')->fridays(); $schedule->command('foo')->saturdays(); $schedule->command('foo')->sundays(); ~~~ ### Prevent Jobs From Overlapping By default, scheduled jobs will be run even if the previous instance of the job is still running. To prevent this, you may use the `withoutOverlapping` method: ~~~ $schedule->command('foo')->withoutOverlapping(); ~~~ In this example, the `foo` command will be run every minute if it is not already running. ### 限制应该执行工作的环境 ~~~ $schedule->command('foo')->monthly()->environments('production'); ~~~ 指定工作在当应用程序处于维护模式也应该执行 ~~~ $schedule->command('foo')->monthly()->evenInMaintenanceMode(); ~~~ ### 只允许工作在闭包返回 true 的时候执行 ~~~ $schedule->command('foo')->monthly()->when(function() { return true; }); ~~~ ### 将预定工作的输出发送到指定的 E-mail ~~~ $schedule->command('foo')->sendOutputTo($filePath)->emailOutputTo('foo@example.com'); ~~~ > 注意: 你必须先把输出存到文件中才可以发送 email。 ### 将预定工作的输出发送到指定的路径 ~~~ $schedule->command('foo')->sendOutputTo($filePath); ~~~ ### 在预定工作执行之后 Ping 一个给定的 URL ~~~ $schedule->command('foo')->thenPing($url); ~~~
';

在命令行接口以外的地方调用命令

最后更新于:2022-04-01 15:13:39

有时你会希望在命令行接口以外的地方执行 Artisan 命令。例如,你可能会希望从 HTTP 路由调用 Artisan 命令。只要使用 `Artisan` facade 即可: ~~~ Route::get('/foo', function() { $exitCode = Artisan::call('command:name', ['--option' => 'foo']); // }); ~~~ 你甚至可以把 Artisan 命令放到队列,他们会通过 [队列工作者](http://www.golaravel.com/laravel/docs/5.0/queues) 在后台执行: ~~~ Route::get('/foo', function() { Artisan::queue('command:name', ['--option' => 'foo']); // }); ~~~
';

用法

最后更新于:2022-04-01 15:13:37

## 列出所有可用的命令 要查看所有可以使用的 Artisan 命令,你可以使用 `list` 命令: ~~~ php artisan list ~~~ ## 浏览命令的帮助画面 每个命令都包含一个显示并描述这个命令能够接受哪些参数和选项的「帮助画面」。要浏览帮助画面,只需要在命令名称前面加上 `help` 即可: ~~~ php artisan help migrate ~~~ ## 指定环境配置 您可以指定要使用的环境配置,只要在执行命令时加上 `--env` 即可切换: ~~~ php artisan migrate --env=local ~~~ ##显示目前的 Laravel 版本 你也可以使用 `--version` 选项,查看目前安装的 Laravel 版本: ~~~ php artisan --version ~~~
';

概览

最后更新于:2022-04-01 15:13:34

#介绍 Artisan 是 Laravel 内置的命令行接口。它提供了一些有用的命令协助您开发,它是由强大的 Symfony Console 组件所驱动。
';

Artisan 命令行工具

最后更新于:2022-04-01 15:13:32

# 简介 //:TODO
';

IDE Helper IDE助手

最后更新于:2022-04-01 15:13:30

#### For Laravel 4.x, check version 1.11 #### Complete phpDocs, directly from the source > 项目地址:https://github.com/barryvdh/laravel-ide-helper Checkout this Laracasts video for a quick introduction/explanation! This package generates a file that your IDE understands, so it can provide accurate autocompletion. Generation is done based on the files in your project, so they are always up-to-date. If you don't want to generate it, you can add a pre-generated file to the root folder of your Laravel project (but this isn't as up-to-date as self generated files). * Generated version: https://gist.github.com/barryvdh/5227822 > Note: You do need CodeIntel for Sublime Text: https://github.com/SublimeCodeIntel/SublimeCodeIntel ## New: PhpStorm Meta for Container instances It's possible to generate a PhpStorm meta file, to add support for factory design pattern. For Laravel, this means we can make PhpStorm understand what kind of object we are resolving from the IoC Container. For example, events will return an Illuminate\Events\Dispatcher object, so with the meta file you can call app('events') and it will autocomplete the Dispatcher methods. ~~~ php artisan ide-helper:meta app('events')->fire(); \App::make('events')->fire(); /** @var \Illuminate\Foundation\Application $app */ $app->make('events')->fire(); ~~~ Pre-generated example: https://gist.github.com/barryvdh/bb6ffc5d11e0a75dba67 > Note: You might need to restart PhpStorm and make sure .phpstorm.meta.php is indexed. Note: When you receive a FatalException about a class that is not found, check your config (for example, remove S3 as cloud driver when you don't have S3 configured. Remove Redis ServiceProvider when you don't use it). ## Automatic phpDoc generation for Laravel Facades Require this package with composer using the following command: ~~~ composer require barryvdh/laravel-ide-helper ~~~ After updating composer, add the service provider to the providers array in `config/app.php` ~~~ 'Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider', ~~~ You can now re-generate the docs yourself (for future updates) ~~~ php artisan ide-helper:generate ~~~ > Note: bootstrap/compiled.php has to be cleared first, so run php artisan clear-compiled before generating (and php artisan optimize after). You can configure your `composer.json` to do this after each commit: ~~~ "scripts":{ "post-update-cmd": [ "php artisan clear-compiled", "php artisan ide-helper:generate", "php artisan optimize" ] }, ~~~ You can also publish the config file to change implementations (ie. interface to specific class) or set defaults for `--helpers` or `--sublime`. ~~~ php artisan vendor:publish --provider=barryvdh/laravel-ide-helper --tag=config ~~~ The generator tries to identify the real class, but if it cannot be found, you can define it in the config file. Some classes need a working database connection. If you do not have a default working connection, some facades will not be included. You can use an in-memory SQLite driver, using the -M option. You can choose to include helper files. This is not enabled by default, but you can override it with the --helpers (-H) option. The Illuminate/Support/helpers.php is already set-up, but you can add/remove your own files in the config file. Automatic phpDocs for models > You need to require doctrine/dbal: ~2.3 in your own composer.json to get database columns. If you don't want to write your properties yourself, you can use the command php artisan ide-helper:models to generate phpDocs, based on table columns, relations and getters/setters. You can write the comments directly to your Model file, using the `--write (-W)` option. By default, you are asked to overwrite or write to a separate file (_ide_helper_models.php). You can force No with `--nowrite (-N)`. Please make sure to backup your models, before writing the info. It should keep the existing comments and only append new properties/methods. The existing phpdoc is replaced, or added if not found. With the `--reset (-R)` option, the existing phpdocs are ignored, and only the newly found columns/relations are saved as phpdocs. ~~~ php artisan ide-helper:models Post /** * An Eloquent Model: 'Post' * * @property integer $id * @property integer $author_id * @property string $title * @property string $text * @property \Carbon\Carbon $created_at * @property \Carbon\Carbon $updated_at * @property-read \User $author * @property-read \Illuminate\Database\Eloquent\Collection|\Comment[] $comments */ ~~~ By default, models in `app/models` are scanned. The optional argument tells what models to use (also outside app/models). ~~~ php artisan ide-helper:models Post User ~~~ You can also scan a different directory, using the `--dir` option (relative from the base path): ~~~ php artisan ide-helper:models --dir="path/to/models" --dir="app/src/Model" ~~~ You can publish the config file (`php artisan vendor:publish`) and set the default directories. Models can be ignored using the --ignore (-I) option ~~~ php artisan ide-helper:models --ignore="Post,User" ~~~ > Note: With namespaces, wrap your model name in " signs: php artisan ide-helper:models "API\User", or escape the slashes (Api\\User)
';

Genertators 代码生成工具

最后更新于:2022-04-01 15:13:27

## 使用自定义代码生成工具快速进行Laravel开发 这个Laravle包提供了一种代码生成器,使得你可以加速你的开发进程,这些生成器包括: * generate:model – 模型生成器 * generate:view – 视图生成器 * generate:controller – 控制器生成器 * generate:seed – 数据库填充器 * generate:migration – 迁移 * generate:pivot – 关联表 * generate:resource -资源 * generate:scaffold – 脚手架 项目地址 > https://github.com/laracasts/Laravel-5-Generators-Extended ## 安装 #### Laravel 4.2 或者更低的版本 使用Composer安装这个包,编辑你项目的composer.json文件,在`require`中添加`way/generators` ~~~ "require-dev": { "way/generators": "~2.0" } ~~~ 然后,在命令行下执行`composer update`: ~~~ composer update --dev ~~~ 一旦这个操作完成,就只需要最后一步,在配置文件中加入服务提供者。打开`app/config/app.php`文件,添加一个新的记录到`providers`数组中. ~~~ 'Way\Generators\GeneratorsServiceProvider' ~~~ 这样就可以了,你已经安装完成并可以运行这个包了。运行artisan命令行则可以在终端上看到`generate`相关命令。 ~~~ php artisan ~~~ #### Laravel 5.0 或者更高版本 使用Composer安装这个包,编辑你项目的`composer.json`文件,在`require`中添加`way/generators` ~~~ "require-dev": { "way/generators": "~3.0" } ~~~ 由于在Laravel高版本中默认文件夹结构,需要3.0或者更高的版本,才能适应5.0版本以上的Laravel 然后,在命令行下执行`composer update`: ~~~ composer update --dev ~~~ 一旦这个操作完成,就只需要最后一步,在配置文件中加入服务提供者。打开`app/config/app.php`文件,添加一个新的记录到`providers`数组中. ~~~ 'Way\Generators\GeneratorsServiceProvider' ~~~ 这样就可以了,你已经安装完成并可以运行这个包了。运行artisan命令行则可以在终端上看到`generate`相关命令。 ~~~ php artisan ~~~ ## 使用示例 想象一下使用一个生成器加速你的工作流。而不是打开models文件夹,创建一个新的文件,保存它,并且在文件中添加一个class,你可以简单的运行一个生成器命令即可完成这一系列动作。 * Migrations 迁移 * Models 模型 * Views 视图 * Seeds 填充 * Pivot 关联表 * Resources 资源 * Scaffolding 脚手架 * Configuration 配置 #### 迁移 Laravel提供了一个迁移生成器,但是它仅仅能够创建数据库结构。让我们再回顾几个例子,使用`generate:migration`。 ~~~ php artisan generate:migration create_posts_table ~~~ 如果我们不指定字段配置项,则下面这个文件将被创建在`app/database/migrations`目录下。 ~~~ <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function(Blueprint $table) { $table->increments('id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('posts'); } } ~~~ > 注意:生成器能够检测到你正在尝试创建一个表。迁移的名称,尽量应该是可描述的。生成器将扫描你的生成器名字的第一个单词,并尽力确定如何继续。例如,对于迁移create_posts_table,关键字"create",意味着我们应该准备必要的架构来创建表。 如果你使用`add_user_id_to_posts_table`代替迁移的名字,在上面的示例中,关键字"`add`",意味着我们将添加一行到现有的表中,然我们看看这个生成器命令。 ~~~ php artisan generate:migration add_user_id_to_posts_table ~~~ 这个命令将会准备一个下面这样的样板: ~~~ <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AddUserIdToPostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function(Blueprint $table) { }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function(Blueprint $table) { }); } } ~~~ > 注意:这一次我们没有做Schema::create #### 关键字 当你在写迁移的名字的时候,使用下面的关键字给生成器提供提示。 * create or make (create_users_table) * add or insert (add_user_id_to_posts_table) * remove (remove_user_id_from_posts_table) * delete or drop (delete_users_table) #### 生成数据库模式 这是非常漂亮的,但是让我们更进一步,生成数据库模式的同时,使用`fields`选项。 ~~~ php artisan generate:migration create_posts_table --fields="title:string, body:text" ~~~ 在我们解释这个选项之前,让我们先看一下输出: ~~~ <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function(Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('body'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('posts'); } } ~~~ 漂亮!少量的提示在这里: * 生成器将默认使用自增的`id`字段作为主键 * 它解析`fields`选项,并添加这些字段 * drop方法能够足够聪明的意识到,在相反的情况下,这个表应该被完全删除 声明字段,使用逗号+空格分隔键值列表[`key:value:option sets`],其中`key`表示字段的名称,`value`表示字段的类型,`option`表示制定索引或者像是`unique`、`nullable`这样的属性。 这里是一些示例: * --fields="first:string, last:string" * --fields="age:integer, yob:date" * --fields="username:string:unique, age:integer:nullable" * --fields="name:string:default('John Doe'), bio:text:nullable" * --fields="username:string(30):unique, age:integer:nullable:default(18)" 请注意最后一个示例,这里我们指定了`string(30)`的字符串限制。这将产生`$table->string('username', 30)->unique()`; 使用生成器删除表是可能的: ~~~ php artisan generate:migration delete_posts_table ~~~ 作为最后一个示例i,让我们运行一个迁移,从`tasks`表中,删除`completed`字段。 ~~~ php artisan generate:migration remove_completed_from_tasks_table --fields="completed:boolean" ~~~ 这一次,我们使用了"`remove`"关键字,生成器知道它要删除一个字段,并且把它添加到`down()`方法中。 ~~~ <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class RemoveCompletedFromTasksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('tasks', function(Blueprint $table) { $table->dropColumn('completed'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('tasks', function(Blueprint $table) { $table->boolean('completed'); }); } } ~~~ ## 模型 ~~~ php artisan generate:model Post ~~~ 这将生成一个文件,app/models/Post.php并且写入下面的样板 ~~~ <?php class Post extends \Eloquent { } ~~~ ## 视图 视图生成器相当简单。 ~~~ php artisan generate:view admin.reports.index ~~~ 这个命令将创建一个空的视图,`/app/views/admin/reports/index.blade.php`。如果提供的文件夹不存在,它会自动帮你创建 `Seeds` 生成数据[译注:应该是用来填充测试数据] Laravel为我们提供了非常灵活的方式来填充表 Laravel provides us with a flexible way to seed new tables. ~~~ php artisan generate:seed users ~~~ 设置你想要生成的生成文件参数。这将生成 `app/database/seeds/UsersTableSeeder.php` 并用一下内容作为填充: ~~~ <?php // Composer: "fzaninotto/faker": "v1.3.0" use Faker\Factory as Faker; class UsersTableSeeder extends Seeder { public function run() { $faker = Faker::create(); foreach(range(1, 10) as $index) { User::create([ ]); } } } ~~~ 这将使用流行的`Faker`库为你提供一个基本的样板。这将是一个非常漂亮的方式来生成你的数据库表。不要忘记使用`Composer`来安装`Faker`! > 关联表[译注:pivot 这个词愿意是中心点、中枢的意思,这里翻译成关联表比较合适,通俗一点就是两个表的mapping关系表,带有外键约束] 当你需要一个关联表时,`generate:pivot`可以加速建立相应的表。 简单的传递两个需要关联的表的名字。对于`orders`和`users`表,你可以: ~~~ php artisan generate:pivot orders users ~~~ 这个命令将创建下面的迁移: ~~~ <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateOrderUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('order_user', function(Blueprint $table) { $table->increments('id'); $table->integer('order_id')->unsigned()->index(); $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade'); $table->integer('user_id')->unsigned()->index(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('order_user'); } } ~~~ > 注意:它会正确设置你提供的两个表名,排名不分先后。现在,运行php artisan migrate来创建你的关联表! ## 资源 `generate:resource`命令将会为你坐一系列的事情: * 生成一个模型 * 生成index, show, create, edit视图 * 生成一个控制器 * 生成一个数据库结构迁移 * 生成一个数据库填充 * 迁移这个数据库 当你触发这个命令,它将对每个动作进行问询。通过这个方式,你可以告诉生成器,哪些是你确实需要的。 例子 想象如果你需要创建一个方法来显示文章。你需要手动创建一个控制器,一个模型,一个数据库迁移并且填充它,并且创建一个数据库填充…为什么不用生成器来做呢? ~~~ php artisan generate:resource post --fields="title:string, body:text" ~~~ 如果你对每个询问说yes,这个命令会给你如下样板: * app/models/Post.php * app/controllers/PostsController.php * app/database/migrations/timestamp-create_posts_table.php (including the schema) * app/database/seeds/PostsTableSeeder.php ## Scaffolding 脚手架 脚手架生成器类似于`generate:resource`,除了创建一些初始化样板外,同时也是为了方便。 例如,在运行`generate:scaffold post`时,你的控制器模板将会将会是: ~~~ <?php class PostsController extends \BaseController { /** * Display a listing of posts * * @return Response */ public function index() { $posts = Post::all(); return View::make('posts.index', compact('posts')); } /** * Show the form for creating a new post * * @return Response */ public function create() { return View::make('posts.create'); } /** * Store a newly created post in storage. * * @return Response */ public function store() { $validator = Validator::make($data = Input::all(), Post::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } Post::create($data); return Redirect::route('posts.index'); } /** * Display the specified post. * * @param int $id * @return Response */ public function show($id) { $post = Post::findOrFail($id); return View::make('posts.show', compact('post')); } /** * Show the form for editing the specified post. * * @param int $id * @return Response */ public function edit($id) { $post = Post::find($id); return View::make('posts.edit', compact('post')); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { $post = Post::findOrFail($id); $validator = Validator::make($data = Input::all(), Post::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $post->update($data); return Redirect::route('posts.index'); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { Post::destroy($id); return Redirect::route('posts.index'); } } ~~~ 请注意我们鼓励您去修改这些自动生成的控制器。它只是一个简单的开始。 `Configuration` 配置 你或许想修改你的模板–自动生成的文件是怎样格式化的。考虑到这一点,你需要发布你的模板,生成器将会使用它们。 ~~~ php artisan generate:publish-templates ~~~ 你要复制所有app/templates目录下的模板。你可以修改这些只要你满意它的格式。如果你喜欢不同的目录: ~~~ php artisan generate:publish-templates --path=app/foo/bar/templates ~~~ 当你运行`generate:publish-templates` ,它也会将配置发布到`app/config/packages/way/generators/config/config.php`文件。这个文件看起来有点像: ~~~ <?php return [ /* |-------------------------------------------------------------------------- | Where the templates for the generators are stored... |-------------------------------------------------------------------------- | */ 'model_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/model.txt', 'scaffold_model_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/scaffolding/model.txt', 'controller_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/controller.txt', 'scaffold_controller_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/scaffolding/controller.txt', 'migration_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/migration.txt', 'seed_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/seed.txt', 'view_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/view.txt', /* |-------------------------------------------------------------------------- | Where the generated files will be saved... |-------------------------------------------------------------------------- | */ 'model_target_path' => app_path('models'), 'controller_target_path' => app_path('controllers'), 'migration_target_path' => app_path('database/migrations'), 'seed_target_path' => app_path('database/seeds'), 'view_target_path' => app_path('views') ]; ~~~ 同时,当你修改这个文件的时候,注意你也可以更新每个默认的生成器目标目录。 ## Shortcuts 快捷命令 因为你可能会一次又一次的键入如下命令,命令别名显然是有意义的。 ~~~ # Generator Stuff alias g:m="php artisan generate:model" alias g:c="php artisan generate:controller" alias g:v="php artisan generate:view" alias g:s="php artisan generate:seed" alias g:mig="php artisan generate:migration" alias g:r="php artisan generate:resource" ~~~ 这些将被保存,例如,你的`~/.bash_profile` 或者 `~/.bashrc` 文件中。 * * * * * 原文地址:[http://www.huyanping.cn/?p=364](http://www.huyanping.cn/?p=364)
';

Shoppingcart 购物车

最后更新于:2022-04-01 15:13:25

还是拿来主义编程思想,既然别人实现了,就不再造轮子了。 `LaravelShoppingcart`是Laravel下的一个购物车实现,项目地址: > https://github.com/Crinsane/LaravelShoppingcart 文档翻译: 针对Laravel 4的简单购物车实现。 ## 安装 通过composer安装,编辑 `composer.json` 文件,如下: #### Laravel4.2及以下 ~~~ "require": { "laravel/framework": "4.2.*", "gloudemans/shoppingcart": "~1.2" } ~~~ #### Laravel5 ~~~ "require": { "laravel/framework": "5.0.*", "gloudemans/shoppingcart": "dev-master" } ~~~ #### 接着运行更新命令 ~~~ composer update ~~~ 添加以下代码到 `app/config/app.php` 的 `service providers` 数组里 ~~~ 'Gloudemans\Shoppingcart\ShoppingcartServiceProvider' ~~~ 添加以下代码到`aliases`数组中 ~~~ 'Cart' => 'Gloudemans\Shoppingcart\Facades\Cart', ~~~ 完成以上工作就可以在你的项目中使用了。 ## 使用 Shoppingcart提供了以下的可用方法: #### Cart:add() ~~~ /** * Add a row to the cart * 向购物车添加新行 * * @param string|Array $id Unique ID of the item|Item formated as array|Array of items * -参数 字符串|数组 $id item的唯一id | Item格式化成数组 | items 数组 * @param string $name Name of the item * -参数 字符串 $name item 名称 * @param int $qty Item qty to add to the cart * -param int $qty 添加到购物车的item的数量 * @param float $price Price of one item * -param float $price item 价格 * @param Array $options Array of additional options, such as 'size' or 'color' * @param Array $options 附加参数数组, 诸如'size' 或 'color' */ // Basic form 基础表单 Cart::add('293ad', 'Product 1', 1, 9.99, array('size' => 'large')); // Array form 数组表单 Cart::add(array('id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 9.99, 'options' => array('size' => 'large'))); // Batch method 批量方法 Cart::add(array( array('id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 10.00), array('id' => '4832k', 'name' => 'Product 2', 'qty' => 1, 'price' => 10.00, 'options' => array('size' => 'large')) )); ~~~ #### Cart:update() ~~~ /** * Update the quantity of one row of the cart * * @param string $rowId The rowid of the item you want to update * @param integer|Array $attribute New quantity of the item|Array of attributes to update * @return boolean */ $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; Cart::update($rowId, 2); OR Cart::update($rowId, array('name' => 'Product 1')); ~~~ #### Cart::remove() ~~~ /** * Remove a row from the cart * * @param string $rowId The rowid of the item * @return boolean */ $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; Cart::remove($rowId); ~~~ #### Cart::get() ~~~ /** * Get a row of the cart by its ID * * @param string $rowId The ID of the row to fetch * @return CartRowCollection */ $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; Cart::get($rowId); ~~~ #### Cart::content() ~~~ /** * Get the cart content * * @return CartCollection */ Cart::content(); ~~~ #### Cart::destroy() ~~~ /** * Empty the cart 清空购物车 * * @return boolean */ Cart::destroy(); ~~~ #### Cart:total() ~~~ /** * Get the price total 获取总价格 * * @return float */ Cart::total(); ~~~ #### Cart:count() ~~~ /** * Get the number of items in the cart * * @param boolean $totalItems Get all the items (when false, will return the number of rows) * @return int */ Cart::count(); // Total items Cart::count(false); // Total rows ~~~ #### Cart::search() ~~~ /** * Search if the cart has a item * * @param Array $search An array with the item ID and optional options * @return Array|boolean */ Cart::search(array('id' => 1, 'options' => array('size' => 'L'))); // Returns an array of rowid(s) of found item(s) or false on failure ~~~ #### Collections 显而易见,`Cart::content()`和`Cart::get()`返回一个集合,`CartCollection`和`CartRowCollection`。 这些集合扩展了原始的`Laravel 4`的`collection`类,所以这个类的所有方法同样的可以被使用在购物车类中。 ## 实例 现在扩展包可以支持多个购物车实例,工作方式像这样: 你可以使用`Cart::instance(‘newInstance’)`设置当前的购物车实例,此刻,有效的购物车实例是`newInstance`,所以你添加、移除或获取购物车内容,操作的都是`newInstance`。如果你需要选择其它实例,你只需要调用`Cart::instance(‘otherInstance’)` ~~~ Cart::instance('shopping')->add('192ao12', 'Product 1', 1, 9.99); // Get the content of the 'shopping' cart Cart::content(); Cart::instance('wishlist')->add('sdjk922', 'Product 2', 1, 19.95, array('size' => 'medium')); // Get the content of the 'wishlist' cart Cart::content(); // If you want to get the content of the 'shopping' cart again... Cart::instance('shopping')->content(); // And the count of the 'wishlist' cart again Cart::instance('wishlist')->count(); ~~~ > 备注1:如果你不重新设置,购物车永远是最后一个实例 > 备注2:默认的购物车实例名称是mian,所以Cart::content();等同于Cart::instance(‘main’)->content()。 ## Models 一个新特性是可以使为购物车的item关联一个模型。假设在你的应用中有一个product模型,通过新的`associate()`方法,可以通知购物车里的项关联到product模型。 这样你可以从 `CartRowCollection` 访问你的模型。 下面是一个示例: ~~~ <?php /** * Let say we have a Product model that has a name and description. */ Cart::associate('Product')->add('293ad', 'Product 1', 1, 9.99, array('size' => 'large')); $content = Cart::content(); foreach($content as $row) { echo 'You have ' . $row->qty . ' items of ' . $row->product->name . ' with description: "' . $row->product->description . '" in your cart.'; } ~~~ 访问模型的主键和关联模型的名称相同。associate()还有第二个参数,是可选的,用于指定模型的命名空间。 ## 异常错误 当发生错误时,购物车模块将抛出异常。使用购物车模块可以很容易的调试错误,或者基于异常的类型处理错误。购物车模块可以抛出以下异常: |Exception|Reason| |---------|------| |ShoppingcartInstanceException|When no instance is passed to the instance() method 没有实例传递给instance()方法| |ShoppingcartInvalidItemException|When a new product misses one of it’s arguments (id,name, qty, price) 当新产品缺少一个参数| |ShoppingcartInvalidPriceException|When a non-numeric price is passed当非数值的价格被传递| |ShoppingcartInvalidQtyException|When a non-numeric quantity is passed当非数值的数量被传递| |ShoppingcartInvalidRowIDException|When the $rowId that got passed doesn’t exists in the current cart当当前的购物车并不存在被传来的$roeid| |ShoppingcartUnknownModelException|When an unknown model is associated to a cart row当一个未知的模型被关联到购物车的行| ## Events 下面是购物车监听的事件: |Event|Fired| |-----|-----| |cart.add($item)|When a single item is added当单个item被添加| |cart.batch($items)|When a batch of items is added当一批item被添加| |cart.update($rowId)|When an item in the cart is updated购物车单个item跟更新| |cart.remove($rowId)|When an item is removed from the cart当一个item被从购物车中移除| |cart.destroy()|When the cart is destroyed当购物车被清空| #### 示例: 下面的示例展示了如果在table中呈现购物车的内容 ~~~ // Controller Cart::add('192ao12', 'Product 1', 1, 9.99); Cart::add('1239ad0', 'Product 2', 2, 5.95, array('size' => 'large')); // View <table> <thead> <tr> <th>Product</th> <th>Qty</th> <th>Item Price</th> <th>Subtotal</th> </tr> </thead> <tbody> <?php foreach($cart as $row) :?> <tr> <td> <p><strong><?php echo $row->name;?></strong></p> <p><?php echo ($row->options->has('size') ? $row->options->size : '');?></p> </td> <td><input type="text" value="<?php echo $row->qty;?>"></td> <td>$<?php echo $row->price;?></td> <td>$<?php echo $row->subtotal;?></td> </tr> <?php endforeach;?> </tbody> </table> ~~~ * * * * * 原文地址:[http://www.zhangxihai.cn/archives/189](http://www.zhangxihai.cn/archives/189)
';

Entrust 权限管理

最后更新于:2022-04-01 15:13:23

## 说明 `Zizaco/Entrust` 是 Laravel 下 用户权限系统 的解决方案, 配合 用户身份认证 扩展包 `Zizaco/confide` 使用, 可以快速搭建出一套具备高扩展性的用户系统. `Confide`, `Entrust `和 `Sentry` 项目地址 > https://github.com/Zizaco/entrust #### 首先两个概念分清楚: * 用户身份认证 `Authentication` - 处理用户登录, 退出, 注册, 找回密码, 重置密码, 用户邮箱认证 etc.. * 权限管理 `Authorization` - 负责 用户 与 权限, 用户组 三者之间的对应, 以及管理. 下面是这几个 Package 的简单区别: * `Sentry` = 用户身份认证 + 权限管理; * `Zizaco/Entrust` = 权限管理; * `Zizaco/confide` = 用户身份认证; 用户身份认证 和 权限管理 分开来做有什么好处呢? 分开的话可以更灵活, 有些项目因为特殊的业务逻辑, 无法使用 `Confide `的 用户身份认证, 但是却需要用到 权限管理, 如: `PHPHub `. Laravel-blog 就是一个简单的应用, 使用了 `Confide` 做 用户身份认证, `Entrust` 做 权限管理, 可以作为参考. ## 安装 * composer.json ~~~ "zizaco/entrust": "1.2.*@dev" ~~~ * install ~~~ composer update ~~~ * provider 修改 `app/config/app.php` 文件, 在 `providers` 数组里面添加: ~~~ 'Zizaco\Entrust\EntrustServiceProvider', ~~~ * aliase 修改 app/config/app.php 文件, 在 aliases 数组里面添加: ~~~ 'Entrust' => 'Zizaco\Entrust\EntrustFacade', ~~~ * 系统配置 Entrust 会利用 config/auth.php 里面的值, 去决定使用那个 Model 和 用户表名. * 生成 Migration ~~~ php artisan entrust:migration ~~~ 会生成 <timestamp>_entrust_setup_tables.php Migration 文件, 检查没问题后: ~~~ php artisan migrate ~~~ * Models 创建 app/models/Role.php 文件, 内容为以下: ~~~ <?php use Zizaco\Entrust\EntrustRole; class Role extends EntrustRole { } ~~~ 创建 app/models/Permission.php 文件, 内容为以下: ~~~ <?php use Zizaco\Entrust\EntrustPermission; class Permission extends EntrustPermission { } ~~~ 修改 app/models/User.php 文件, 添加 HasRole trait: ~~~ <?php use Zizaco\Entrust\HasRole; class User extends Eloquent /* or ConfideUser 'wink' */{ use HasRole; // Add this trait to your user model ... ~~~ 最后, 生成自动加载: ~~~ composer dump-autoload ~~~ ## 基础概念 三个主要数据对象, 以及他们之间的关系: * User - 用户, 一个用户可以属于多个用户组, 不直接挂钩权限, 让用户组和权限绑定; * Roles - 用户组, 一个用户组可以拥有多个权限; * Permission - 权限; 四个数据库表说明: 安装的第 6 步会产生一个 Migration, 此文件定义了 4 张数据库表: * roles - 用户组信息表; * assigned_roles - 用户和用户组之间的对应关系; * permissions - 权限信息表; * permission_role - 权限和用户组之间的对应关系. ## 实例 接下来我们来创建用户组和权限, 并授权用户 创建用户组 ~~~ $admin = new Role; $admin->name = 'Admin'; $admin->save(); $owner = new Role; $owner->name = 'Owner'; $owner->save(); ~~~ #### 创建权限 ~~~ $manageUsers = new Permission; $manageUsers->name = 'manage_users'; $manageUsers->display_name = 'Manage Users'; $manageUsers->save(); $managePosts = new Permission; $managePosts->name = 'manage_posts'; $managePosts->display_name = 'Manage Posts'; $managePosts->save(); ~~~ #### 添加用户组权限 ~~~ $owner->perms()->sync(array($managePosts->id, $manageUsers->id)); $admin->perms()->sync(array($managePosts->id)); ~~~ #### 添加用户到用户组 ~~~ // 获取用户 $user = User::where('username','=','Zizaco')->first(); // 可以使用 Entrust 提供的便捷方法用户授权 // 注: 参数可以为 Role 对象, 数组, 或者 ID $user->attachRole( $admin ); // 或者使用 Eloquent 自带的对象关系赋值 $user->roles()->attach( $admin->id ); // id only ~~~ ## 使用 #### 基本权限判断 判断用户是否属于某个用户组: ~~~ $user->hasRole("Owner"); // false $user->hasRole("Admin"); // true ~~~ 判断用户是否拥有某个权限 (通过用户组): ~~~ $user->can("manage_posts"); // true $user->can("manage_users"); // false ~~~ 使用 ability 方法同时判断多个权限和用户组 ~~~ $user->ability(['Admin','Owner'], ['manage_posts','manage_users']); // 或者 $user->ability('Admin,Owner', 'manage_posts,manage_users'); ~~~ #### 路由过滤 Entrust 还提供帮助方法, 用来做路由过滤: ~~~ // 有 `manage_posts` 权限的用户, 才能访问 `admin/posts` 开头的链接 Entrust::routeNeedsPermission( 'admin/post*', 'manage_posts' ); // 属于 `Owner` 用户组的人, 才能访问 `admin/advanced*` 开头的链接 Entrust::routeNeedsRole( 'admin/advanced*', 'Owner' ); // 可以在第二个选项传参数组, 当前用户需要符合所有传参的用户组或者权限, // 才能授权成功 Entrust::routeNeedsPermission( 'admin/post*', ['manage_posts','manage_comments'] ); Entrust::routeNeedsRole( 'admin/advanced*', ['Owner','Writer'] ); ~~~ ## 总结 一般我会在 `Migration` 里初始化基本的用户组, 见 Laravel Blog 项目里面的 `Entrust Migration` . ## 参考 > PHPHub 和 Laravel-Blog 都使用 Entrust 进行用户权限管理, 可以作为参考; * * * * * 原文地址:[https://phphub.org/index.php/topics/166](https://phphub.org/index.php/topics/166)
';

Confide 用户身份认证

最后更新于:2022-04-01 15:13:20

Confide提供了认证模块,包含了登录、注册、退出、密码重置等功能。 项目地址 > https://github.com/zizaco/confide `暂时未支持Laravel 5` 英文通读水平有限,记下为妙,文档瞎翻如下(意译): Confide针对Laravel提供了全套的身份验证解决方案,它可以减少涉及用户管理的重复工作。包含创建账户,登陆,登出,E-MAIL验证密码重置等有用的功能。 Confide的目标是简单易用,快速配置和灵活使用。 > 注意:如果你使用的是MongoDB,请使用Confide Mongo > https://github.com/Zizaco/confide-mongo ## 产品特点: #### 当前: 1. 账号确认(通过确认链接)。 2. 密码确认(发送一封带有重设密码链接的EMAIL)。 3. 简单方便的创建登陆,注册和密码重设的表单。 4. 为登陆,注册,密码重设,确认等生成路由。 5. 生成一个可定制的控制器,包含了基础的用户账户行为。 6. 包含一组用于帮助解决用户基本特性的方法。 7. 集成了`Laravel Auth`和`Reminders component/configs`. 8. 用户验证。 9. 登陆控制。 10. 验证后跳转至先前的路由。 11. 检查注册中独特的email和username。 如果你需要的是用户角色和权限控制请看`Entrust` > 警告: 默认会发送一封确认邮件用于验证用户的邮件地址。在confide的config文件可以改变这个设置,将signup_email和 signup_confirm设置为false,就不必发送邮件并验证邮件地址了。 ## 快速开始 #### 需要的设置 在composer.json文件的require键中加入如下代码 "zizaco/confide": "~4.3@dev" #### 运行Composer更新命令 $ composer update 将 `Zizaco\Confide\ServiceProvider` 添加到 `app/config/app.php` 的 `providers` 数组的后面 ~~~ 'providers' => array( 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', ... 'Zizaco\Confide\ServiceProvider', ), ~~~ 将 `'Confide' => 'Zizaco\Confide\Facade'` 加入到 `app/config/app.php` 的 `aliases` 数组的末尾 ~~~ 'aliases' => array( 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', ... 'Confide' => 'Zizaco\Confide\Facade', ), ~~~ #### 配置 在`app/config/auth.php`中设置属性值。这个值将被confide用于生成数据库迁移以及生成工资器和路由。 在`config/mail.php`设置右键地址和名称,他们将被用于向用户发送账户验证和密码重设右键。 #### 用户模型 现在生成Confide迁移和密码提醒表的迁移: ~~~ $ php artisan confide:migration ~~~ 将生成_confide_setup_users_table.php的迁移。你可以使用 artisan migrate 命令运行它: ~~~ $ php artisan migrate ~~~ 将会生成一张包含`email`, `password`, `remember_token`, `confirmation_code` 和`confirmed `列的表,这些都是Confide需要使用的默认字段。你还可以自由的向此表添加更多的字段。 将你在 app/models/User.php 中的用户模型变成: ~~~ <?php use Zizaco\Confide\ConfideUser; use Zizaco\Confide\ConfideUserInterface; class User extends Eloquent implements ConfideUserInterface { use ConfideUser; } ?> ~~~ `ConfideUser`特性将会妥善的处理用户模型的的一些行为。 #### 装储默认的访问 最后,你可以为confide装储默认的控制器, 知识库以及默认路由. ~~~ $ php artisan confide:controller $ php artisan confide:routes ~~~ 别忘记运行以下命令对自动加载进行优化 ~~~ $ composer dump-autoload ~~~ 准备好出发了吗. 使用 `http://yourapp/users/create` 创建你的第一用户,打开 `app/routes.php` 查看可用的路由。你需要确认最新创建的用户(通过”`reaching`”他自身的`confirm`()方法),除此之外你可以再配置中禁用登陆要求验证的配置(看下面)。 ## 详细使用说明 #### 基本设置: 1. `config/database.php` 中配置的数据库连接需要正确地运行。 2. `config/auth.php` 中的模型和表的名称要正确,因为会被Confide一直使用(特别是生成迁移和控制器)。 3. `from` 配置在 `config/mail.php` 中。 #### 配置: 1. `‘Zizaco\Confide\ServiceProvider’` 和 `‘Confide’ => ‘Zizaco\Confide\Facade’` 分别加入 `config/app.php` 的 `‘providers’` 和 d 数组里。 2. 用户模型 (在 `config/auth.php` 中相同名称) 需要实现 `Zizaco\Confide\ConfideUserInterface` 接口. 这样可以使 `forgotPassword()` and `confirm()` 这些方法变可用。 #### 可选步骤: 1. 可选地你可以在你的用户模型使用 `Zizaco\Confide\ConfideUser` 特性。这个特性将会为用户启用`”confide’s default”`,这会节约很多时间。如果你期待更多的定制你可以编写自己的代码。 2. 使用`Confide facade`可以轻松的使用 `makeLoginForm()` 和 `makeSignupForm()` 生成`login`和`signup`表单。你可以使用如下代码展现你的表单`{{ Confide::makeLoginForm()->render() }}`. 3. 如果需要从Confide模板生成控制器和知识库,可以使用 `$ php artisan confide:controller` 命令。如果当前已经存在相同名称的控制器,不会覆盖。 4. 使用 `$ php artisan confide:routes` 可以从Confide模板生成匹配控制器的路由。别担心,你的路由不会被覆盖。 ## 高级 #### UserRepository类 你可能已经注意到当生成控制器的时候同样会创建一个`UserRepository`类。这个类包含一些不属于”`controoler`”目标的代码,将你的类变的更干净和更有可测试性。如果你还是不明白这个类为什么不存在,我推荐你使用”`Creating flexible Controllers in Laravel 4 using Repositories`”(在Laravel4中使用仓库生成弹性控制器)搜索google。 #### 使用自定义的类,表以及模型名称 你可以修改`config/auth.php`文件中关联用户的的模型名称。Confide目前使用在该配置文件中的值。 在从controller模板生成控制器时可以使用`–name`参数改变控制器名称。 ~~~ $ php artisan confide:controller --name=Employee ~~~ 结果会是 EmployeeController 接着,当生成路由的时候, 你需要使用 `–controller` 参数来匹配已经存在的controller. ~~~ $ php artisan confide:routes --controller=Employee ~~~ 你也可以使用带namespace命名空间的控制器 ~~~ $ php artisan confide:controller --name=MyProject\\Auth\\User ~~~ > 警告: 在bash中,你需要使用双反斜杠符号’\\’ 。会得到这样的 MyProject\Auth\UserController 路径。当然生成文件将加入到命名空间等同的文件目录(原谅我不会翻译这句)。 #### 使用自定义表单和邮箱 首先,发布配置文件: ~~~ $ php artisan config:publish zizaco/confide ~~~ 然后在`app/config/packages/zizaco/confide/config.php`文件中修改视图名称。 #### 比对 要比对你的用户表你还需要添加password_confirmation和confirmation_code字段。例如 ~~~ class UsersTableSeeder extends Seeder { public function run() { $user = new User; $user->email = 'johndoe@site.dev'; $user->password = 'foo_bar_1234'; $user->password_confirmation = 'foo_bar_1234'; $user->confirmation_code = md5(uniqid(mt_rand(), true)); $user->confirmed = 1; if(! $user->save()) { Log::info('Unable to create user '.$user->email, (array)$user->errors()); } else { Log::info('Created user '.$user->email); } } } ~~~ #### 自定义用户验证 你可以通过创建一个类实行你自己的验证器,它需要实现了`UserValidatorInterface`接口和注册为类似”`confide.user_validator`”的类。 例如,创建你自己的验证器类: ~~~ // app/models/MyOwnValidator.php class MyOwnValidator implements UserValidatorInterface { public function validate(ConfideUserInterface $user) { unset($user->password_confirmation); return true; // If the user valid } } ~~~ 然后在IoC容器里注册为 “confide.user_validator” ~~~ // app/start/global.php //... App::bind('confide.user_validator', 'MyOwnValidator'); ~~~ 同样的,在保存之前别忘记你的验证器需要复原’password_confirmation’属性。 #### 给”make”方法传递额外的信息 如果你想给已经渲染的表单传递额外的参数,你可以使用另外一种语法来实现这一目标。 #### 替代使用make方法: ~~~ Confide::makeResetPasswordForm($token): ~~~ 你可以使用: ~~~ View::make(Config::get('confide::reset_password_form')) ->with('token', $token); ~~~ 它产生相同的输出,但是你可以像其它视图一样使用width来添加更多输入。 #### RESTful controller 如果你想生成一个 `RESTful controller` 你可以使用 `–restful` 或 `-r` 参数项。 ~~~ $ php artisan confide:controller --restful ~~~ 将会得到一个 RESTful controller 接着生成路由的时候,需要使用–resful参数来匹配已经存在的路由。 ~~~ $ php artisan confide:routes --restful ~~~ #### 用户角色和权限 为了使Confide的代码量不至于膨胀,角色和权限使用另外一个扩展包:Entrust `Entrust`和`Confide`是一对好基友。 ~~~ See Entrust - https://github.com/Zizaco/entrust ~~~ 在登陆后跳转至预设好的路由 在定义你的筛选器的时候你需要使用`Redirect::guest(‘users/login’)`。例如: ~~~ // filters.php Route::filter('auth', function () { // If the user is not logged in 如果用户没登陆 if (Auth::guest()) { return Redirect::guest('users/login'); } }); // Only authenticated users will be able to access routes that begins with // 'admin'. Ex: 'admin/posts', 'admin/categories'. Route::when('admin*', 'auth'); ~~~ 或者,你在使用Entrust :) ~~~ // filters.php Entrust::routeNeedsRole('admin*', 'Admin', function () { return Redirect::guest('users/login'); }); ~~~ 最终,如果你在控制器的`users/login function`中使用了 `Redirect:intended(‘a/default/url/here’)`,成功登陆后会默认跳转。生成的控制器已经完成了这些。 #### 故障排除 > [2014-07-18 01:13:15] production.ERROR: exception ‘Illuminate\Database\QueryException’ with message ‘SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘password_confirmation’ in ‘field list’ (SQL: insert into users … 在发送到数据库前需要将`password_confirmation`从项目中移除。保证你的用户模型实现了`ConfideUserInterface`接口,如上所述他使用了`ConfideUser `特性。除此之外,如果你使用了自定义的验证器,你需要在保存用户前复原`password_confirmation`。 我需要我的用户有 “username” 当生成confide和controller迁移的时候使用–username参数。 ~~~ $ php artisan confide:migration --username ... $ php artisan confide:controller --username ~~~ 如果你想让username变成必填项,你需要扩展UserValidator和重写$rules属性。 当我尝试登陆的时候我收到 “Your account may not be confirmed” (你的账号没有确认) 你需要验证最新创建的用户 (by “reaching” its confirm() method),除此之外你可以再配置文件中取消必须验证的配置。 你可以很轻松的验证用户,通过使用Laravel的artisan修补工具。 我没法生成带有命名空间的控制器 在bash中,你需要使用双反斜杠符号’\\’。 ~~~ $ php artisan confide:controller --name=MyProject\\Auth\\User ~~~ 用户不用验证账号就能登录 如果你想只有验证的用户才能登录,在你的UserController中,用`logAttempt( $input, true )`代替用`logAttempt( $input )`。第二个参数代表”`confirmed_only`”。 当我运行`composer update`更新的时候,我的应用崩溃了 Confide 4.0.0 是一个巨大的所有代码都被重写的更新。一些类改变,生成器被改进为了匹配某些更好的实务(比如代码库和分开验证器类)。查看下面的Release Notes。 如果你有一个遗产项目使用了较老的Confide版本。别担心,你永远可以在composer.json指定一个早先的版本。 例如: `“zizaco/confide”: “~3.2″`将会避免下载4.0版本。只会下载3.2终极版。 * * * * * 原文地址:[http://www.zhangxihai.cn/archives/160](http://www.zhangxihai.cn/archives/160)
';

开发包

最后更新于:2022-04-01 15:13:18

# 简介 收集、推荐好玩的Laravel开发包 |包名|描述|项目地址| |-----------------| |Confide|用户身份认证|[GitHub](https://github.com/zizaco/confide)| |Entrust|权限管理|[GitHub](https://github.com/Zizaco/entrust)| |Shoppingcart|购物车|[GitHub](https://github.com/Crinsane/LaravelShoppingcart)| |Genertators|代码生成工具|[GitHub](https://github.com/laracasts/Laravel-5-Generators-Extended)| |IDE Helper|IDE代码提示助手|[GitHub](https://github.com/barryvdh/laravel-ide-helper)|
';

管道

最后更新于:2022-04-01 15:13:16

当你想要一次发送很多命令到服务器时可以使用管道。使用 `pipeline` 方法: 发送多个命令到服务器 ~~~ Redis::pipeline(function($pipe) { for ($i = 0; $i < 1000; $i++) { $pipe->set("key:$i", $i); } }); ~~~
';

使用方式

最后更新于:2022-04-01 15:13:13

你可以经由 `Redis::connection` 方法得到 Redis 实例: ~~~ $redis = Redis::connection(); ~~~ 你会得到一个使用 Redis 默认服务器的实例。如果你没有使用服务器集群,你可以在 `connection` 方法传入定义在 Redis 配置文件的服务器名称,以连到特定服务器: ~~~ $redis = Redis::connection('other'); ~~~ 一旦你有了 Redis 客户端实例,就可以使用实例发出任何 Redis 命令。Laravel 使用魔术方法传递命令到服务器: ~~~ $redis->set('name', 'Taylor'); $name = $redis->get('name'); $values = $redis->lrange('names', 5, 10); ~~~ 注意,传入命令的参数仅只是传递到魔术方法里。当然,你不一定要使用魔术方法,你也可以使用 `command` 方法传递命令到服务器: ~~~ $values = $redis->command('lrange', [5, 10]); ~~~ 若你只想对默认服务器下命令,可以使用 Redis 类的静态魔术方法: ~~~ Redis::set('name', 'Taylor'); $name = Redis::get('name'); $values = Redis::lrange('names', 5, 10); ~~~ > 提示: 也可以使用 Redis 作为 Laravel 的 缓存 和 会话 驱动。
';

配置

最后更新于:2022-04-01 15:13:11

应用程序的 Redis 配置文件在 `config/database.php`。在这个文件里,你会看到 redis 数组,里面有应用程序使用的 Redis 服务器数据: ~~~ 'redis' => array( 'cluster' => true, 'default' => array('host' => '127.0.0.1', 'port' => 6379), ), ~~~ 默认的服务器配置对于开发应该是足够的。然而,你可以根据使用环境自由修改数组数据。只要给每个 Redis 一个名称,并且配置服务器的 host 和 port。 `cluster` 选项会让 Laravel 的 Redis 客户端在所有 Redis 节点间执行客户端分片( `client-side sharding` ),让你建立节点池,并因此拥有大量的 RAM 可用。然而,客户端分片的节点不能执行容错转移;因此,这主要适合用可以从另一台主要数据保存库取得的缓存数据。 如果你的 Redis 服务器需要认证,你可以在 Redis 服务器配置文件里加入 `password` 为键值的参数配置。
';

Redis

最后更新于:2022-04-01 15:13:09

# 简介 `Redis` 是开源,先进的键值对保存库。由于它可用的键包含了 字串、哈希、列表、集合 和 有序集合,因此常被称作数据结构服务器。 在使用 `Redis` 之前,你需要经由 `Composer` 将 `predis/predis` 扩展包装在 Laravel 中。 > 提醒: 如果你用 PECL 安装了 Redis PHP extension,则需要重命名 config/app.php 里的 Redis 别名。
';

数据填充

最后更新于:2022-04-01 15:13:07

Laravel 可以简单的使用 `seed` 类,填充测试数据到数据库。所有的 `seed` 类放在 `database/seeds` 目录下。可以使用任何你想要的类名称,但是应该遵守某些大小写规范,如 `UserTableSeeder` 之类。默认已经有一个 `DatabaseSeeder` 类。在这个类里,使用 `call` 方法执行其他的 `seed` 类,让你控制填充的顺序。 ## Seed 类例子 ~~~ class DatabaseSeeder extends Seeder { public function run() { $this->call('UserTableSeeder'); $this->command->info('User table seeded!'); } } class UserTableSeeder extends Seeder { public function run() { DB::table('users')->delete(); User::create(['email' => 'foo@bar.com']); } } ~~~ 要执行数据填充,可以使用 Artisan CLI 的 db:seed 命令: ~~~ php artisan db:seed ~~~ 默认 `db:seed` 命令会执行 `DatabaseSeeder`,可以使用它来调用其他 `seed` 类,不过,也可以使用 `--class` 参数指定要单独执行的类: ~~~ php artisan db:seed --class=UserTableSeeder ~~~ 你也可以使用 `migrate:refresh` 命令填充数据,它会回滚并且再次执行所有迁移: ~~~ php artisan migrate:refresh --seed ~~~
';

回滚迁移

最后更新于:2022-04-01 15:13:04

## 回滚上一次的迁移 ~~~ php artisan migrate:rollback ~~~ ## 回滚所有迁移 ~~~ php artisan migrate:reset ~~~ ## 回滚所有迁移并且再执行一次 ~~~ php artisan migrate:refresh php artisan migrate:refresh --seed ~~~
';