Laravel5.0學習--01 入門


本文以laravel5.0.22為例。

生產環境建議使用laravel5.1版本,因為該版本是長期支持版本。5.1文檔更詳細:http://laravel-china.org/docs/5.1。

環境需求

Laravel5.0 框架有一些系統上的需求:

PHP 版本 >= 5.4
Mcrypt PHP 擴展
OpenSSL PHP 擴展
Mbstring PHP 擴展
Tokenizer PHP 擴展

在 PHP 5.5 之后, 有些操作系統需要手動安裝 PHP JSON 擴展包。如果你是使用 Ubuntu,可以通過 apt-get install php5-json 來進行安裝。

我該使用Laravel嗎

來自知乎網友的討論:PHP框架Laravel還是Codeigniter? https://www.zhihu.com/question/21617669

CI比較接近原生的PHP,在原有PHP代碼的基礎上封裝了很多類,因為它架構簡單,所以容易擴展。從另一個角度來看,也就是沒啥架構,最最原始的三層架構。

Laravel 簡直就是一次創新,大量吸收了Java,RoR等其他框架的精華,在架構方面,已基本做到現有Php框架最佳,擴展性,伸縮性強大得一塌糊塗,非常適合團隊作戰。

對於新手來說,Laravel初看上去不太像Php的原本寫法了,所謂優雅,就是你光憑代碼就可以知道意思,而不用讀注釋,代碼精簡復用度非常高;Laravel開發人員都是PHP圈子最頂尖的高手,他們習慣用新的技術和架構,即便如此,Laravel其實上手並不難,一旦以你掌握了它的大致要點后,你會逐漸發現它在每一個方面都全面超越CI,且實用性非常高。(來源:知乎)

簡單建議:
如果是個人項目,旨在研究,推薦Laravel;如果是外包或者公司項目,推薦Codeigniter或者ThinkPHP。

特點

RESTful Routing ;
設計精妙的 Blade 模板引擎, 輕快, 不失靈活 ;
合理的 ORM model 層, Eloquent ORM , 借鑒於 Rails 的成功;
migration 數據庫版本系統 和 seeding ;
使用包管理器 Composer , 打開了一扇開往春天的門;
強調測試驅動, 整個核心經受過完整的測試, 高質量的代碼;
命令行驅動, 可以做到高度自動化 (講究效率, 代碼生成器...) , 借鑒與 rails ;
合理使用 PHP 的新版本特性, 讓寫代碼更加有樂趣, 跟上時代的步伐;
積極向上的社區, 這個很重要呀, 大家都在學習着, 創造着好的工具, 加快開發速度, 提高編程效率, 接受新知識的速度也很快.
對 php 標准化的支持 PHP-FIG — PHP Framework Interop Group

更多閱讀:
1、最好的 PHP 框架是什么?為什么? - Charlie Jade 的回答 - 知乎
https://www.zhihu.com/question/19558755/answer/23062110

2、php - Laravel框架相對於其他框架比如CI、TP、Symfony等的優勢是什么? - SegmentFault
https://segmentfault.com/q/1010000000489103

安裝

使用Composer安裝

很多人會卡在這一步。要么是不會Composer,要么就是無法使用Composer安裝。

如果還不知道Composer,先去學習了解了解:

1、Composer使用 - 飛鴻影~ - 博客園
http://www.cnblogs.com/52fhy/p/5246013.html
2、Packagist / Composer 中國全量鏡像
http://pkg.phpcomposer.com/
3、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

來源:http://www.golaravel.com/download/

項目結構

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 框架有一個目錄需要額外配置權限:storagevendor 目錄要讓服務器有寫入的權限。

路由(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

1、輸出:使用雙花括號: {{$name}}
2、繼承:@extends,將copy一份母視圖過來。
引入:@include('shared.errors')引入子視圖
3、區域替換:@section...@endsection,該標簽內的內容將替換在母視圖使用@yield定義的內容。
4、條件語句:@if...@endif

@if (count($records) === 1)
    我有一條記錄!
@elseif (count($records) > 1)
    我有多條記錄!
@else
    我沒有任何記錄!
@endif

5、數據遍歷、循環:

@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

6、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
        ));
    }

7、public目錄下資源引用

{{asset('/css/main.css')}}

對應public目錄下的css/main.css
8、視圖可以顯示PHP 函數的結果。實際上,可以放置任何想要的 PHP 代碼到 Blade 顯示的語法里面:

目前的 UNIX 時間戳為 {{ time() }}。

9、禁用渲染
由於許多 JavaScript 框架也使用「大括號」在瀏覽器中顯示指定的表達式,因此可以使用 @ 符號來告知 Blade 渲染引擎該表達式應該維持原樣。舉個例子:

Hello, @{{ name }}.

10、缺省值:

{{ isset($name) ? $name : 'Default' }}

# 或者
{{ $name or 'Default' }}

11、顯示未轉義過的數據
默認輸出的值會自動調用 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 中文文檔:

  1. http://laravel-china.org/docs/5.0
  2. http://laravel-china.org/docs/5.1
  3. http://www.golaravel.com/laravel/docs/5.0/

更多:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM