Laravel5.0學習--01 入門
本文以laravel5.0.22爲例。php
生產環境建議使用laravel5.1版本,由於該版本是長期支持版本。5.1文檔更詳細:http://laravel-china.org/docs/5.1。css
環境需求
Laravel5.0 框架有一些系統上的需求:html
PHP 版本 >= 5.4
Mcrypt PHP 擴展
OpenSSL PHP 擴展
Mbstring PHP 擴展
Tokenizer PHP 擴展mysql
在 PHP 5.5 以後, 有些操做系統須要手動安裝 PHP JSON 擴展包。若是你是使用 Ubuntu,能夠經過 apt-get install php5-json 來進行安裝。laravel
我該使用Laravel嗎
來自知乎網友的討論:PHP框架Laravel仍是Codeigniter? https://www.zhihu.com/question/21617669git
CI比較接近原生的PHP,在原有PHP代碼的基礎上封裝了不少類,由於它架構簡單,因此容易擴展。從另外一個角度來看,也就是沒啥架構,最最原始的三層架構。github
Laravel 簡直就是一次創新,大量吸取了Java,RoR等其餘框架的精華,在架構方面,已基本作到現有Php框架最佳,擴展性,伸縮性強大得一塌糊塗,很是適合團隊做戰。sql
對於新手來講,Laravel初看上去不太像Php的本來寫法了,所謂優雅,就是你光憑代碼就能夠知道意思,而不用讀註釋,代碼精簡複用度很是高;Laravel開發人員都是PHP圈子最頂尖的高手,他們習慣用新的技術和架構,即使如此,Laravel其實上手並不難,一旦以你掌握了它的大體要點後,你會逐漸發現它在每個方面都全面超越CI,且實用性很是高。(來源:知乎)typescript
簡單建議:
若是是我的項目,旨在研究,推薦Laravel;若是是外包或者公司項目,推薦Codeigniter或者ThinkPHP。數據庫
特色
RESTful Routing ;
設計精妙的 Blade 模板引擎, 輕快, 不失靈活 ;
合理的 ORM model 層, Eloquent ORM , 借鑑於 Rails 的成功;
migration 數據庫版本系統 和 seeding ;
使用包管理器 Composer , 打開了一扇開往春天的門;
強調測試驅動, 整個核心經受過完整的測試, 高質量的代碼;
命令行驅動, 能夠作到高度自動化 (講究效率, 代碼生成器...) , 借鑑與 rails ;
合理使用 PHP 的新版本特性, 讓寫代碼更加有樂趣, 跟上時代的步伐;
積極向上的社區, 這個很重要呀, 你們都在學習着, 創造着好的工具, 加快開發速度, 提升編程效率, 接受新知識的速度也很快.
對 php 標準化的支持 PHP-FIG — PHP Framework Interop Group
更多閱讀:
一、最好的 PHP 框架是什麼?爲何? - Charlie Jade 的回答 - 知乎
https://www.zhihu.com/question/19558755/answer/23062110
二、php - Laravel框架相對於其餘框架好比CI、TP、Symfony等的優點是什麼? - SegmentFault
https://segmentfault.com/q/1010000000489103
安裝
使用Composer安裝
不少人會卡在這一步。要麼是不會Composer,要麼就是沒法使用Composer安裝。
若是還不知道Composer,先去學習瞭解瞭解:
一、Composer使用 - 飛鴻影~ - 博客園
http://www.cnblogs.com/52fhy/p/5246013.html
二、Packagist / Composer 中國全量鏡像
http://pkg.phpcomposer.com/
三、Composer 中文網
http://www.phpcomposer.com/
若是沒法使用用Composer安裝,頗有多是倉庫訪問不了,即被牆了。先更新Composer倉庫源:
# 修改 composer 的全局配置文件(推薦方式)
# 打開命令行窗口(windows用戶)或控制檯(Linux、Mac 用戶)並執行以下命令:
composer config -g repo.packagist composer https://packagist.phpcomposer.com
接下來正式開始安裝吧!
這裏以Laravel 5.0 版本爲例(PHP 版本 >=
5.4)。
# 指定5.0.22版本,項目目錄是learnlaravel5
composer create-project laravel/laravel learnlaravel5 5.0.22
等待安裝(須要5分鐘左右):
Installing laravel/laravel (v5.0.22)
- Installing laravel/laravel (v5.0.22)
Downloading: 100%
Created project in learnlaravel5
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
- Installing jakub-onderka/php-console-color (0.1)
Downloading: 100%
- Installing vlucas/phpdotenv (v1.1.0)
Downloading: 100%
- Installing symfony/var-dumper (v2.6.4)
Downloading: 100%
- Installing symfony/translation (v2.6.4)
Downloading: 100%
- Installing symfony/security-core (v2.6.4)
Downloading: 100%
- Installing symfony/routing (v2.6.4)
Downloading: 100%
- Installing symfony/process (v2.6.4)
Downloading: 100%
- Installing symfony/http-foundation (v2.6.4)
Downloading: 100%
- Installing symfony/event-dispatcher (v2.6.4)
Downloading: 100%
- Installing psr/log (1.0.0)
Downloading: 100%
...
Generating autoload files
> php artisan clear-compiled
> php artisan optimize
Generating optimized class loader
Compiling common classes
> php -r "copy('.env.example', '.env');"
> php artisan key:generate
Application key [4FunRLeVWE0jc6QTs3h8vNbDnoa4Qi8Q] set successfully.
安裝完即可以訪問了:
http://localhost/laravel5/public/index.php
一鍵安裝包下載
一鍵安裝包是在 Laravel 官方 GitHub 倉庫源碼的基礎上安裝了依賴庫(也就是已經作過 composer install,已經有了 vendor 目錄),對於剛接觸 Laravel 或者使用 Composer 受挫的用戶可以提供快速上手實踐 Laravel 的捷徑。
Laravel 一鍵安裝包。更新時間:2016年3月7日下午3點04分
master 7.45M http://down.golaravel.com/laravel/laravel-master.zip
v5.2.15 7.46M http://down.golaravel.com/laravel/laravel-v5.2.15.zip
v5.1.11 7.97M http://down.golaravel.com/laravel/laravel-v5.1.11.zip
v5.0.22 5.94M http://down.golaravel.com/laravel/laravel-v5.0.22.zip
v4.2.11 5.06M http://down.golaravel.com/laravel/laravel-v4.2.11.zip
v4.1.27 4.60M http://down.golaravel.com/laravel/laravel-v4.1.27.zip
v4.0.9 6.05M http://down.golaravel.com/laravel/laravel-v4.0.9.zip
項目結構
app
|---Commands
|---Console
|---Events
|---Exceptions
|---Handlers
|---Http
|---Controllers 控制器
|---Middleware 中間件
|---Requests 請求
|---routes.php 路由
|---Providers
|---Services
|---User.php 模型文件
bootstrap
config
database
public
resources
|---lang
|---views 視圖
|---welcome.blade.php
|---home.blade.php
storage
|---logs
tests
vendor
.env
artisan
composer.json
server.php
Laravel 框架有一個目錄須要額外配置權限:storage
和 vendor
目錄要讓服務器有寫入的權限。
路由(Route)
路由文件在:app/Http/routes.php
。
默認的配置:
Route::get('/', 'WelcomeController@index');//匹配根目錄到WelcomeController/index
Route::get('home', 'HomeController@index');//匹配home到HomeController/index
Route::controller('blog', 'BlogController');//匹配BlogController裏的全部方法,但控制器裏方法必須以get、post開頭
//路由組
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
控制器(Controllers)
控制器路徑:app/Http/Controllers
。
示例:WelcomeController.php
<?php
namespace App\Http\Controllers;
class WelcomeController extends Controller {
public function index()
{
return view('welcome');
}
}
繼承自根控制器:Controller.php
<?php namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesCommands; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; abstract class Controller extends BaseController { use DispatchesCommands, ValidatesRequests; }
生成url
url()方法能夠生成符合規範的url。
echo url('greeting');
//輸出:http://localhost/laravel5/public/index.php/greeting
配置
配置文件:.env
,包含了數據庫和MAIL等配置。
config
目錄下也有相關配置。
模型(Model)
與Laravel4系列不一樣,舊的 app/models
目錄已經徹底被移除。相對的,Laravel5模型文件都放在 app
目錄下,以及默認使用 App
命名空間。
示例:Blog.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Blog extends Model { public function listAll(){ return $this->all(); } }
視圖(views)
視圖根路徑:resources/views
。
視圖與控制器對應關係:
例如:控制器裏
view('welcome'); //對應視圖根路徑下welcome.blade.php
view('admin.pages.edit', $data); //對應對應視圖根路徑下admin/pages/edit.blade.php
視圖文件代碼上實際就是html。但自定義了一些標籤。
在視圖文件,咱們可使用PHP原生語法來獲取傳過來的數據:
<html> <body> <h1>Hello, <?php echo $name; ?></h1> </body> </html>
或者使用Laravel的Blade模板標籤:雙大括號:
<html> <body> <h1>Hello, {{$name}}</h1> </body> </html>
控制器(WelcomeController.php)裏是這樣的:
public function greeting() {
return view('greeting', ['name' => 'James']);
}
注意,測試的時候要新建路由:
Route::get('greeting', 'WelcomeController@greeting');
訪問:http://localhost/laravel5/public/index.php/greeting
傳遞數據到視圖
// 使用傳統的方法
$view = view('greeting')->with('name', 'Victoria');
// 使用魔術方法
$view = view('greeting')->withName('Victoria');
模板標籤語言
示例文件:
layout.blade.php 母視圖
<html> <body> <h1>Laravel Quickstart</h1> @yield('content') </body> </html>
users.blade.php 普通視圖
@extends('layout')
@section('content')
Users!
@endsection
一、輸出:使用雙花括號: {{$name}}
。
二、繼承:@extends
,將copy一份母視圖過來。
引入:@include('shared.errors')
引入子視圖
三、區域替換:@section
...@endsection
,該標籤內的內容將替換在母視圖使用@yield
定義的內容。
四、條件語句:@if
...@endif
。
@if (count($records) === 1)
我有一條記錄!
@elseif (count($records) > 1)
我有多條記錄!
@else
我沒有任何記錄!
@endif
五、數據遍歷、循環:
@for ($i = 0; $i < 10; $i++)
目前的值爲 {{ $i }}
@endfor
@foreach ($users as $user)
<p>此用戶爲 {{ $user->id }}</p>
@endforeach
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>沒有用戶</p>
@endforelse
@while (true)
<p>我永遠都在跑循環。</p>
@endwhile
六、url生成:示例
{{ url('blog/detail/'.$item->id) }}
# 或者
{{ url('blog/detail',array('id'=>$item->id)) }}
控制器裏方法括號裏接這個參數:
public function getDetail($id){
$blog = new Blog();
$detail = $blog->find($id);
return view('detail', array(
'detail' => $detail
));
}
七、public目錄下資源引用
{{asset('/css/main.css')}}
對應public目錄下的css/main.css
八、視圖能夠顯示PHP 函數的結果。實際上,能夠放置任何想要的 PHP 代碼到 Blade 顯示的語法裏面:
目前的 UNIX 時間戳爲 {{ time() }}。
九、禁用渲染
因爲許多 JavaScript 框架也使用「大括號」在瀏覽器中顯示指定的表達式,所以可使用 @
符號來告知 Blade 渲染引擎該表達式應該維持原樣。舉個例子:
Hello, @{{ name }}.
十、缺省值:
{{ isset($name) ? $name : 'Default' }}
# 或者
{{ $name or 'Default' }}
十一、顯示未轉義過的數據
默認輸出的值會自動調用 PHP 的 htmlentities 函數,以免 XSS 攻擊。禁用:
Hello, {!! $name !!}.
參考:Laravel 5.1 中文文檔:Blade 模板
http://laravel-china.org/docs/5.1/blade
數據庫操做
Laravel中提供DB facade、查詢構造器和Eloquent ORM三種數據庫操做方式。本文接下來將講解前兩種方式。
數據庫相關配置文件都在 config/database.php
。默認從.env
文件中讀取配置。
目前 Laravel 支持四種數據庫系統: MySQL、Postgres、SQLite、以及 SQL Server。
讀寫分離:
'mysql' => [
'read' => [
'host' => '192.168.1.1',
],
'write' => [
'host' => '196.168.1.2'
],
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],
使用DB類進行CURD
須要先引入。
use Illuminate\Support\Facades\DB;
例如:
public function greeting() {
$results = DB::select('select * from blog where id = ?', [1]);
print_r($results);exit;
}
輸出:
Array ( [0] => stdClass Object ( [id] => 1 [uid] => 1 [title] => test [content] => hello laravel5! [flag] => 1 [create_time] => 0 [update_time] => 0 ) )
更多方法(來自官方文檔):
//執行 Select 查找
$results = DB::select('select * from users where id = ?', [1]);
$results = DB::select('select * from users where id = :id', ['id' => 1]);
//執行 Insert 語法
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
//執行 Update 語法
DB::update('update users set votes = 100 where name = ?', ['John']);
執行 Delete 語法
DB::delete('delete from users');
//執行通常語法
DB::statement('drop table users');
//監聽查找事件
DB::listen(function($sql, $bindings, $time) {
//
});
//數據庫事務處理
//你可使用 transaction 方法,去執行一組數據庫事務處理的操做:
DB::transaction(function() {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
//手動事務
DB::beginTransaction();
DB::rollback();
DB::commit();
//獲取鏈接
//若要使用多個鏈接,能夠經過 DB::connection 方法取用:
$users = DB::connection('foo')->select(...);
//你也能夠取用原始底層的 PDO 實例:
$pdo = DB::connection()->getPdo();
//有時候你可能須要從新鏈接到特定的數據庫:
DB::reconnect('foo');
//若是你由於超過了底層 PDO 實例的 max_connections 的限制,須要關閉特定的數據庫鏈接,能夠經過 disconnect 方法:
DB::disconnect('foo');
//查找日誌記錄
//Laravel 能夠在內存裏訪問此次請求中全部的查找語句。然而在有些例子下要注意,好比一次添加 大量的數據,可能會致使應用程序耗損過多內存。 若是要啓用日誌,可使用 enableQueryLog 方法:
DB::connection()->enableQueryLog();
//要獲得執行過的查找紀錄數組,你可使用 getQueryLog 方法:
$queries = DB::getQueryLog();
DB類查詢構造器
Laravel 查詢構造器使用 PDO 參數綁定,以保護應用程序免於 SQL 注入,所以傳入的參數不需額外轉義特殊字符。
示例:
//獲取全部數據列
$users = DB::table('users')->get();
查詢:
//根據條件查找,取得單一數據列
$user = DB::table('users')->where('name', 'John')->first();
var_dump($user->name);
//從數據表中取得單一數據列的單一字段
$name = DB::table('users')->where('name', 'John')->pluck('name');
//取得單一字段值的列表:這個方法將會返回數據表 role 的 title 字段值的數組
$roles = DB::table('roles')->lists('title');
$roles = DB::table('roles')->lists('title', 'name');
//指定查詢字段
$users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('users')->distinct()->get();
$users = DB::table('users')->select('name as user_name')->get();
//增長查詢字段到現有的查詢中
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
//使用 where 及運算符
$users = DB::table('users')->where('votes', '>', 100)->get();
//or
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
//Between
$users = DB::table('users')
->whereBetween('votes', [1, 100])->get();
//Not Between
$users = DB::table('users')
->whereNotBetween('votes', [1, 100])->get();
//In
$users = DB::table('users')
->whereIn('id', [1, 2, 3])->get();
//NotIn
$users = DB::table('users')
->whereNotIn('id', [1, 2, 3])->get();
//Null 找有未配置的值的數據
$users = DB::table('users')
->whereNull('updated_at')->get();
//魔術語句
$admin = DB::table('users')->whereId(1)->first();
$john = DB::table('users')
->whereIdAndEmail(2, 'john@doe.com')
->first();
$jane = DB::table('users')
->whereNameOrAge('Jane', 22)
->first();
//排序(Order By)、分羣(Group By) 及 Having
$users = DB::table('users')
->orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
//偏移(Offset) 及 限制(Limit)
$users = DB::table('users')->skip(10)->take(5)->get();
//基本的 Join 語法
DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.id', 'contacts.phone', 'orders.price')
->get();
//Left Join 語法
DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
//更高級的 join 子句:
DB::table('users')
->join('contacts', function($join) {
$join->on('users.id', '=', 'contacts.user_id')->orOn(...);
})
->get();
DB::table('users')
->join('contacts', function($join) {
$join->on('users.id', '=', 'contacts.user_id')
->where('contacts.user_id', '>', 5);
})
->get();
//羣組化參數
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query) {
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
//上面的查找語法會產生下方的 SQL:
select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
//Exists 語法
DB::table('users')
->whereExists(function($query) {
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
//上面的查找語法會產生下方的 SQL:
select * from users
where exists (
select 1 from orders where orders.user_id = users.id
)
//使用聚合方法
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
$price = DB::table('orders')->min('price');
$price = DB::table('orders')->avg('price');
$total = DB::table('users')->sum('votes');
新增:
//新增,不會返回新增ID
DB::table('users')->insert(
['email' => 'john@example.com', 'votes' => 0]
);
//新增,返回新增ID
$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);
//批量新增
DB::table('users')->insert([
['email' => 'taylor@example.com', 'votes' => 0],
['email' => 'dayle@example.com', 'votes' => 0]
]);
更新:
//更新
DB::table('users')
->where('id', 1)
->update(['votes' => 1]);
//自增或自減一個字段的值
DB::table('users')->increment('votes');
DB::table('users')->increment('votes', 5);
DB::table('users')->decrement('votes');
DB::table('users')->decrement('votes', 5);
//也可以同時指定其餘要更新的字段:
DB::table('users')->increment('votes', 1, ['name' => 'John']);
刪除:
//刪除數據表中的數據
DB::table('users')->where('votes', '<', 100)->delete();
//刪除數據表中的全部數據
DB::table('users')->delete();
//清空數據表
DB::table('users')->truncate();
更多查看:http://laravel-china.org/docs/5.0/queries
Eloquent ORM
相比DB類,Laravel 的 Eloquent ORM 提供優雅的 ActiveRecord 實現來和數據庫的互動。 每一個數據庫表會有一個對應的模型文件。
詳見下一章。
學習資料
推薦教程:
Laravel 5 系列入門教程(一)【最適合中國人的 Laravel 教程】 - 歲寒
https://lvwenhan.com/laravel/432.html
Laravel 5 中文文檔:
- http://laravel-china.org/docs/5.0
- http://laravel-china.org/docs/5.1
- http://www.golaravel.com/laravel/docs/5.0/
更多:
-
Laravist |Laravel Vuejs Bootstrap 視頻教程
https://laravist.com/ -
LaraBase——全棧工程師之家
http://laravelbase.com/ -
Laravel - The PHP Framework For Web Artisans
http://laravel.com/ -
laravel/laravel
https://github.com/laravel/laravel