On Github lifesign / laravel_slide
2014年php开发框架流行度排名
Github Star
First Commit
Author: Taylor Otwell
....
// app/routes.php
Route::get('/', function(){
return View::make('hello');
})
其他请求呢?
Route::post('foo/bar', function(){
return 'Post Request';
})
Route::any('foo', function(){
return 'Any Request';
});
很多时候往往路由不是静态的地址, 而是带有动态的参数. 比如blog/{$category}
Route::get('blog/{category}', function($category){
return "Finding Post in {$category}";
});
可选参数
Route::get('blog/{category?}', function($category = null){
if ($category)
//fetch blogs in this category
else
//fetch all blogs
return View::make('blog', /* $blogs */);
});
顾名思义是给路由进行命名, 有什么好处呢?
Route::get('user/{id}', ['as' => 'user.detail', function($id){
//
}]);
//define filter
Route::filter('login', function()
{
// Some Logic check if the current user is login
});
在特定的路由前进行过滤 使用 before 关键字
Route::get('money', ['before' => 'login', function(){
// see user's money
}]);
如果不想为每个路由定义相同的过滤器, 我们可以采用群组路由的方式
Route::group(['before' => 'csrf'], function(){
Route::post('login', function(){});
Route::post('user/profile', function(){});
});
Route::get('user/{id}', 'UserController@showProfile');
控制器
class UserController extends BaseController {
/**
* Show the profile for the given user.
*/
public function showProfile($id)
{
$user = User::find($id);
return View::make('user.profile', ['user' => $user]);
}
}
Route::resource('photo', 'PhotoController');
// 获取所有任务记录
$tasks = Task::all();
// 获取ID为1的任务
$task = Task::find(1);
// 更新ID为1的task
$task = Task::find(1);
$task->title = 'Finish Homework';
$task->save();
// 创建一条任务
Task::create([
'title' => 'Write article'
]);
// 删除任务
Task::find(1)->delete();
One To One Example
class User extends Eloquent {
public function phone()
{
return $this->hasOne('Phone');
}
}
$phone = User::find(1)->phone;
SQL执行
select * from users where id = 1 select * from phones where user_id = 1
One To Many Example
class Task extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
class User extends Eloquent {
public function tasks()
{
return $this->hasMany('Task');
}
}
// Get all tasks by the author with an id of 1 $tasks = User::find(1)->tasks; // Get the author of a task $author = Task::find(5)->user()->username; // Insert a new task by author $task = new Task([ title: 'Go to store.' ]); User::find(1)->tasks()->insert($task);
//需要手动指定一堆的键值 为的是预防多余字段插入
News::create([
'title' => Input::get('title'),
'slug' => Input::get('slug'),
'content' => Input::get('content'),
'published_at' => Input::get('published_at'),
])
一个常见的场景
有没有更简单直观的做法呢?
通过定义fillable属性 - "白名单"
class News extends Eloquent {
protected $fillable = array('title', 'slug', 'content', 'published_at');
}
定义Guarded属性 - "黑名单"
class News extends Eloquent {
protected $guarded = array('id');
}
Finally:
News::create(Input::get());
Eloquent_Model_Name::Event_Name(callback)
//创建或者修改post模型的时候自动加入编辑的人的id
Post::creating(function($post)
{
$post->created_by = Auth::user()->id;
$post->updated_by = Auth::user()->id;
});
Post::updating(function($post)
{
$post->updated_by = Auth::user()->id;
});
//删除图片
Image::deleting(function($image)
{
if (count($image->galleries)) return false;
});
如果我们对一个模型注册了很多的事件, 可以为这个模型单独注册一个模型的观察者。
class UserObserver {
public function creating($model) {}
public function updating($model) {}
public function saved($model) {}
}
使用 observe 方法注册一个观察者的实例 User::observe(new UserObserver)
允许动态的对模型进行获取和修改
class User extends Eloquent {
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
}
echo User::find(1)->firstName; // jack->Jack
class User extends Eloquent {
public function setPasswordAttribute()
{
return md5( $this->password );
}
}
"Laravel 所提供的一个简单却又非常强大的模板引擎。Blade 是使用 模板继承(template inheritance) 及 区块(sections) 来创建出视图。所有的 Blade 模板的后缀名都要命名为 .blade.php。"
<!-- Stored in app/views/layouts/master.blade.php -->
<html>
<body>
@include('layouts.partial.nav')
@section('sidebar')
This is the master sidebar.
@show
<div class="container">
@yield('content')
</div>
</body>
</html>
@extends('layouts.master')
@section('sidebar')
<!-- 如果需要调用父类的section 用@parent关键字 -->
@parent
<p>This is appended to the master sidebar.</p>
@stop
@section('content')
<!-- {{}} 输出变量 {{{}}}过滤内容中的 HTML 字符串实体 -->
Hello, {{ $name }}. {{{age}}}
<p>This is my body content.</p>
@stop
@if (count($records) === 1)
I have one record!
@elseif (count($records) > 1)
I have multiple records!
@else
No Records.
@endif
@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}
@endfor
@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach
@while (true)
<p>looping forever.</p>
@endwhile
来个栗子
php artisan migrate:make create_users_table --table=users --create
<!-- store in app/database/migrations/2014_12_19_095403_create_users_table -->
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('name');
$table->integer('age');
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
}
执行操作 php artisan migrate
执行回滚 php artisan rollback
重置操作 php artisan reset
//入口
class DatabaseSeeder extends Seeder {
public function run()
{
//调用UserTableSeeder的run方法 一个表一个seeder
$this->call('UserTableSeeder');
// $this->call('OtherTableSeeder');
$this->command->info('User table seeded!');
}
}
//使用faker作为假数据生成器
use Faker\Factory as Faker;
class UserTableSeeder extends Seeder {
public function run()
{
$faker = Faker::create();
foreach(range(1, 50) as $index)
{
User::create([
'github_id' => $index,
'github_url' => $faker->url(),
'city' => $faker->city(),
'name' => $faker->userName(),
'introduction' => $faker->sentence(),
'email' => $faker->email(),
]);
}
}
}
执行: php artisan db:seed
php artisan route
php >= 5.3.2 openssl √ (win下使用php套件的同学注意多个php.ini问题)
$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer
$ composer
/ ____/___ ____ ___ ____ ____ ________ _____
/ / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
/_/
Composer version d79f2b0fd33ee9b89f3d9f1969f43dc3d570a33a 2014-09-10 15:11:05
Usage:
[options] command [arguments]
...
{
"require": {
"monolog/monolog": "1.2.*"
}
}
在项目目录中执行 composer install
在代码初始化的部分引入下面的代码:
require 'vendor/autoload.php'
PSR 是由 FIG制定的php规范, 简称PSR。
为什么要制定规范?
本组织旨在通过讨论我们代码项目的共同点以找出一个协作编程的方法。
目前发布的规范如下
Vagrant 是一款用来构建虚拟开发环境的工具, 非常适合来做 web 开发。
我们可以通过 Vagrant 封装一个 Linux的开发环境, 分发给团队成员。成员可以在自己喜欢的桌面系统(Mac/Windows/Linux)上开发程序, 代码却能统一在封装好的环境里运行, 而不用担心由于所在系统环境造成的未知bug。
$ vagrant init hashicorp/precise32 $ vagrant up
Laravel 官方定制的 vagrant 包, 包含常用一套完整的开发环境