Artisan 是 Laravel 的命令行接口的名稱允瞧,它提供了許多實(shí)用的命令來幫助你開發(fā) Laravel 應(yīng)用枚抵,它由強(qiáng)大的 Symfony Console 組件所驅(qū)動(dòng)檩坚。
自定義命令默認(rèn)存儲(chǔ)在 app/Console/Commands
目錄中疙赠,當(dāng)然交掏,只要在 composer.json
文件中的配置了自動(dòng)加載枫浙,你可以自由選擇想要放置的地方刨肃。
若要?jiǎng)?chuàng)建新的命令,你可以使用 make:console
Artisan 命令生成命令文件:
php artisan make:console SendEmails
上面的這個(gè)命令會(huì)生成 app/Console/Commands/SendEmails.php
類箩帚,--command
參數(shù)可以用來指定調(diào)用名稱:
php artisan make:console SendEmails --command=emails:send
代碼示例:
<?php
namespace App\Console\Commands;
use App\Store\AdminStore;
use App\Tools\Common;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
/**
注冊(cè)超級(jí)管理員命令
Class CreateAdministrator
@package App\Console\Commands
-
@author 李景磊
*/
class CreateAdministrator extends Command
{
// 生明變量
protected $signature = "administrator:create";// 聲明變量
protected $description = "創(chuàng)建后臺(tái)超級(jí)管理員";// 聲明變量
protected static $adminStore;// 依賴注入
public function __construct(AdminStore $adminStore)
{
self::$adminStore = $adminStore;
parent::__construct();
}public function handle()
{
// 創(chuàng)建管理員
self::create();
}/*
*創(chuàng)建管理員-
*/
public function create()
{
// 接收數(shù)據(jù)
$email = $this->ask('請(qǐng)輸入郵箱');
$password = $this->ask('請(qǐng)輸入密碼');// 顯示接收的數(shù)據(jù)在控制臺(tái)
$this ->info('郵箱:'.$email);
$this ->info('密碼:'.$password);// 判斷是否注冊(cè)
if ($this->confirm('確認(rèn)注冊(cè)嗎真友?')){
$this->info('正在注冊(cè)...');// 獲取接收到的數(shù)據(jù) $data = [ 'email' => $email, 'password' =>$password ]; // 參數(shù)驗(yàn)證規(guī)則 $validator = Validator::make($data,[ 'email' =>'required|email|min:6|max:64', 'password' =>'required|min:6|max:128', ]); // 驗(yàn)證是否是合法數(shù)據(jù) if ($validator->fails()) { $errors = $validator->errors(); $this->table(['錯(cuò)誤'],(array) $errors->toArray()); self::create(); return ; } // 判斷郵箱是否以注冊(cè) $emailRes = self::$adminStore->getOneData(['email' => $email,'status' => 1 ]); if (!empty($emailRes)) { $this->error('已注冊(cè),請(qǐng)更換郵箱紧帕!'); self::create(); return; } // 拼接數(shù)據(jù) $data['guid'] = Common::getUuid(); $data['password'] = Common::cryptString($data['email'], $data['password']); $data['sroce'] = 1; $data['status'] = 1; $data['addtime'] = $_SERVER['REQUEST_TIME']; // 寫入數(shù)據(jù)庫 $res = self::$adminStore->addData($data); // 判斷是否注冊(cè)成功 if (!empty($res)) { $this->info('注冊(cè)成功'); }else{ $this->error('注冊(cè)失敗'); self::create(); }
}else{
$this->info('取消注冊(cè)');
}
}
}
記得在Kernel.php中引用下面這句話盔然;
Commands\CreateAdministrator::class,
-
在store層寫方法
第一個(gè)方法(查找一條數(shù)據(jù))
public function getOneData($where , $id = '')
{
if (empty($where)) {
return false;
}
if (empty($id)) {
return DB::table(self::$table)->where($where)->first();
}
return DB::table(self::$table)->where($where)->where('guid','!=',$id)->first();
}
第2個(gè)方法(添加到數(shù)據(jù)庫)
public function addData($data)
{
if (empty($data)) {
return false;
}
return DB::table(self::$table)->insert($data);
}