composer create-project laravel/laravel learnlaravel5 --prefer-dist v5.3.*
> Illuminate\Foundation\ComposerScripts::postUpdate > php artisan optimize Generating optimized class loader The compiled class file has been removed. > php artisan key:generate Application key [base64:z6FDVhrWJfYFyjjFpJp3tmIsbqvcSAPHsHjDBN3oNpE=] set successfully.
tree
├── app │ ├── Console │ │ └── Kernel.php │ ├── Exceptions │ │ └── Handler.php │ ├── Http │ │ ├── Controllers │ │ │ ├── Auth │ │ │ │ ├── ForgotPasswordController.php │ │ │ │ ├── LoginController.php │ │ │ │ ├── RegisterController.php │ │ │ │ └── ResetPasswordController.php │ │ │ └── Controller.php │ │ ├── Kernel.php │ │ └── Middleware │ │ ├── EncryptCookies.php │ │ ├── RedirectIfAuthenticated.php │ │ └── VerifyCsrfToken.php │ ├── Providers │ │ ├── AppServiceProvider.php │ │ ├── AuthServiceProvider.php │ │ ├── BroadcastServiceProvider.php │ │ ├── EventServiceProvider.php │ │ └── RouteServiceProvider.php │ └── User.php ├── artisan ├── bootstrap │ ├── app.php │ ├── autoload.php │ └── cache ├── composer.json ├── config │ ├── app.php │ ├── auth.php │ ├── broadcasting.php │ ├── cache.php │ ├── compile.php │ ├── database.php │ ├── filesystems.php │ ├── mail.php │ ├── queue.php │ ├── services.php │ ├── session.php │ └── view.php ├── database │ ├── factories │ │ └── ModelFactory.php │ ├── migrations │ │ ├── 2014_10_12_000000_create_users_table.php │ │ └── 2014_10_12_100000_create_password_resets_table.php │ └── seeds │ └── DatabaseSeeder.php ├── gulpfile.js ├── package.json ├── phpunit.xml ├── public │ ├── css │ │ └── app.css │ ├── favicon.ico │ ├── index.php │ ├── js │ │ └── app.js │ ├── robots.txt │ └── web.config ├── readme.md ├── resources │ ├── assets │ │ ├── js │ │ │ ├── app.js │ │ │ ├── bootstrap.js │ │ │ └── components │ │ │ └── Example.vue │ │ └── sass │ │ ├── app.scss │ │ └── _variables.scss │ ├── lang │ │ └── en │ │ ├── auth.php │ │ ├── pagination.php │ │ ├── passwords.php │ │ └── validation.php │ └── views │ ├── errors │ │ └── 503.blade.php │ ├── vendor │ └── welcome.blade.php ├── routes │ ├── api.php │ ├── console.php │ └── web.php ├── server.php ├── storage │ ├── app │ │ └── public │ ├── framework │ │ ├── cache │ │ ├── sessions │ │ └── views │ └── logs └── tests ├── ExampleTest.php └── TestCase.php
- app/Console 主要是和自定義Artisan命令相關
- app/Exceptions 異常捕獲相關,能夠編寫自定義異常
- app/Http/Controllers 控制器相關
- app/Http/Middleware 中間件,進入控制器以前,能夠對URL進行攔截作權限判斷,登陸判斷等
- app/Http/request 默認不存在,能夠經過命令生成,主要是和參數驗證相關
- app/Http/Providers 服務提供者類
- app/Http/Jobs 默認不存在,能夠經過命令生成,用於存放隊列任務。能夠將耗時任務放到這裏
- bootstrap 啓動時,須要加載一些必要的文件
- config 存放配置文件,也能夠自定義配置文件
- database 數據庫相關,能夠經過代碼生成數據庫表和產生一些測試數據
- public/index,php 系統默認入口文件,須要在服務器端指定
- resources 資源文件
- routes 路由文件,laravel的路由會有一個統一的入口文件,就是在這裏配置的
- Route::get($uri, $callback);
- Route::post($uri, $callback);
- Route::put($uri, $callback);
- Route::patch($uri, $callback);
- Route::delete($uri, $callback);
Route::group(['namespace'=>'Admin','prefix'=>'api'],function() { //Admin 命名空間 api 路由前綴 Route::post('/admin/test1', 'AdminController@tes1'); Route::get('/admin/test2', 'AdminController@tes2'); Route::get('/admin/test3', 'AdminController@test3'); Route::group(['middleware' => ['login.auth']], function () { // 使用 login.auth 中間件 Route::Get('/admin/index', 'TestController@index'); Route::Put('/admin/update', 'MemberController@update'); Route::post('/admin/store', 'MemberController@store'); }); });
php artisan make:middleware checkAge
<?php namespace App\Http\Middleware; use Closure; class checkAge { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $input = $request->input(); if(!isset($input['age']) || $input['age']>120){ $return_value = array( 'code' =>config('statuscode.parameter_error'), 'message' =>'error', ); return response()->json($return_value); } return $next($request); } }
protected $routeMiddleware = [ 'checkAge'=>\App\Http\Middleware\AuthorityAuth::class, ];
php artisan make:controller Admin/LoginController.php
Route::get('foo', 'Admin\LoginController@method');
use Illuminate\Support\Facades\Response;
return response()->json($return_value); return response()->jsonp($return_value);
return response($content) ->header('Content-Type', $type) ->header('X-Header-One', 'Header Value') ->header('X-Header-Two', 'Header Value');
return response($content) ->header('Content-Type', $type) ->cookie('name', 'value', $minutes);
php artisan make:request LoginRequest
public function authorize() { return true; } public function response(array $errors) { $fields = array(); foreach($errors as $key=>$error){ } $return_value = array( 'code' =>config('statuscode.parameter_error'), 'fields' =>$fields ); return response()->json($return_value); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'data.param1' =>'required', 'data.param2' =>'required|in:1,2,3', 'data.param3' =>'required', ]; }
use App\Http\Requests\LoginRequest.php; public function login(LoginRequest $request){ }
目錄/app/Exceptions下有一個Handle.php文件 這裏可有兩個方法能夠捕獲異常
- report 方法用於記錄異常或將其發送到外部服務
$reflector = new \ReflectionClass($exception); $exception_name = $reflector->getShortName(); if($exception_name !== 'ValidationException'){ $file = $exception->getFile(); $line = $exception->getLine(); $message = $exception->getMessage(); $error = array( 'exception_name' =>$exception_name, 'uri' =>\Request::getRequestUri(), 'file' =>$file, 'line' =>$line, 'message' =>$message, ); ExceptionLog::error('Exception',$error,'exception'); }
- render 方法負責將異常轉換成 HTTP 響應發送給瀏覽器
$reflector = new \ReflectionClass($exception); $exception_name = $reflector->getShortName(); $file = $exception->getFile(); $line = $exception->getLine(); $message = $exception->getMessage(); $exception_value = array( 'code' =>config('statuscode.fail_server'), 'fields'=>array( 'server_error'=>array( 'field' =>'server_error', 'message' =>$message, 'file' =>$file, 'line' =>$line ) ) ); $return_value = array( 'code' =>'500', 'message' =>'/error?code=500', 'file' =>$file, 'line' =>$line, 'error_message' =>$message, ); return response()->json($return_value);
生成文件php
php artisan make:command Task #app/Console/Commands目錄下會生成一個Task.php文件
打開文件 並編輯 修改文件以下css
protected $signature = 'Task:Calculate'; ##命令 protected $description = 'Calculate Data'; ##描述 public function handle() { sleep(1); echo "Calculate Data"; ##計算任務 }
註冊命令vue
## 編輯 app/Console/Kernel.php protected $commands = [ \App\Console\Commands\Task::class ];
查看命令linux
root@ubuntu:/www# php artisan --list | grep Task Task Task:Calculate Calculate Data
運行命令laravel
php artisan Task:Calculate ##輸出calculate data
laravel 實現了 IOC註冊了特定的服務 這裏經過curl插件作一下演示 服務提供者須要在每一個環境下都要加載,只要把它放在這個數組下面就能夠了
1.安裝web
composer require ixudra/curl ##經過composer安裝插件
2.註冊服務sql
Ixudra\Curl\CurlServiceProvider::class ##編輯 config/app.php文件 在providers文件中添加服務
3.使用數據庫
use Ixudra\Curl\Facades\Curl; $response = Curl::to('http://local.laravel.com/api') ->get();
利用linux的crontab 能夠部署不一樣的任務 若是有多個任務須要部署 則須要編輯多個crontab任務 laravel的 app/Console/Kernel.php文件 提供了一個 schedule 方法 這裏能夠定義不一樣的時間 執行不一樣的命令
//天天凌晨2點執行計算任務 $schedule->command('Task:Calculate') ->withoutOverlapping() ->dailyAt('2:00'); //每小時執行計算任務 $schedule->command('Task:Calculate') ->hourly();
但願根據不一樣環境加載 則編輯app/Providers/AppServiceProvider 文件
public function register() { if ($this->app->environment() !== 'production') { $this->dbQuerySql();; } public function dbQuerySql(){ \DB::listen( function ($sql) { foreach ($sql->bindings as $i => $binding) { if ($binding instanceof \DateTime) { $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\''); } else { if (is_string($binding)) { $sql->bindings[$i] = "'$binding'"; } } } if(env('DEBUG_SQL_INSERT')){ //只記錄 insert sql語句 $sql_type = strstr($sql->sql,"insert"); if(!$sql_type) return; } $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql); $query = vsprintf($query, $sql->bindings); $log = array( 'query'=>$query, ); Log::debug('sql_log',$log,'sql_log'); } ); } }
laravel實現了隊列服務 目的是將耗時的任務延時處理 從而儘快返回請求 隊列支持數據庫,Redis等類型。 配置文件在config/queue.php文件中
使用數據庫來驅動隊列json
php artisan queue:table //生成數據庫隊列的 migration php artisan migrate //建立該數據庫隊列表
php artisan make:job SleepJob
隊列建立完成以後 會在app/Jobs目錄下生成一個SleepJob.php文件
public function handle() { //在handle方法中執行耗時操做 $value = array( 'time'=>date('Y-m-d H:i:s') ); file_put_contents('./tmp.log',json_encode($value).PHP_EOL,FILE_APPEND); sleep(2); }
dispatch(new \App\Jobs\SleepJob());
- 編輯.env文件QUEUE_DRIVER=database
{ "displayName":"App\Jobs\SleepJob", "job":"Illuminate\Queue\CallQueuedHandler@call", "maxTries":null, "timeout":null, "data":{ "commandName":"App\Jobs\SleepJob", "command":"O:17:"App\Jobs\SleepJob":4:{s:6:"*job";N;s:10:"connection";N;s:5:"queue";N;s:5:"delay";N;}" } }
$ php artisan queue:work Processing: App\Jobs\SleepJob
隊列數據執行完成以後 會自動從數據庫中移出
隊列的數據 只會加載一次 若是修改了代碼則須要重啓隊列
$ php artisan queu:restart Broadcasting queue restart signal.
爲了防止隊列掛掉 則能夠配合守護進程