laravel 4 fwdays
TRANSCRIPT
Как выглядит разработка сегодня
Выбирается framework (или это может быть требования от заказчика)
Требования от заказчика транслируются в бизнес-логику
Profit!
Существующие решения
LARAVEL 4
Laravel 4: установка
composer create-project laravel/laravel your-project-name --prefer-dist
composer global require "laravel/installer=~1.1"laravel new PROJECT-NAME
Используем composer для установки
Используем Laravel installer
Laravel 4: некоторые особенности
● Гибкий роутинг● DI/IoC● События● Поддержка нескольких видов кеширования● Работа с очередями● Авторизация● Мощная ORM на базе ActiveRecord● Консольная утилита● Тесты
Laravel 4: Routing
Route::get(‘/’, function () {echo “Hello world!”;
});
Route::get(‘/data’, ‘DataController’);Route::post(‘/data’, ‘DataController@storeData’);
Route::model('user', 'User', function () {throw new UserNotFoundException();
});Route::get(‘/user/{user}’, function (User $user) {
});
Route::resource(‘/object’, ‘ControllerName’);
Замыкание
Контроллер
RESTful контроллер
Привязка модели
Laravel 4: Routing
Route::group(array(‘before’ => ‘auth’), function() { Route::get('/settings', function() { // });});
Route::filter(‘auth’, function() { if(Auth::guest()) {
return Redirect::to(‘/login’); }});
Laravel 4: Controllers
class HomeController extends Controller {
public function index() { return View::make('index'); }
}
Laravel 4: Controllersuse App\Models\UserService;
class HomeController extends Controller { private $userService;
public function __construct(UserService $userService) { $this->userService = $userService; }
public function index() { $currentUser = $this->userService->getUser(); return View::make('index'); }
}
Laravel 4: шаблонизатор
● реализация шаблонов используя PHP. Файл с шаблоном должен иметь расширение *.php
● реализация шаблонов используя встроенный шаблонизаторе Blade. Файл с шаблоном должен иметь формат: *.blade.php
Laravel 4: шаблонизатор
Возможности шаблонизатора blade● создание шаблонов, состоящие из слоев● вывод данных● IF statements, циклы● подключение других представлений
Laravel 4: формы
{{ Form::open(‘url’ => ‘/login’, ‘method’ => ‘post’) }}{{ Form::open(‘action’=>‘AuthController@login’, ‘method’ => ‘post’) }}{{ Form::open(‘route’ => ‘route.login’, ‘method’ => ‘post’) }}
{{ Form::close() }}
{{ Form::model($user, array(‘user.update’ => $user->id)) }}
{{ Form::close() }}
● Form::label● Form::text● Form::password● Form::email● Form::file● Form::checkbox
● Form::selectRange● Form::radio● Form::number● Form::select● Form::submit● Form::macro
Laravel 4: валидация данных
$validator = Validator::make($input, $rules, $messages);$validator = Validator::make( array('name' => 'Test'), array('name' => 'required|min:5'), array('name.min' => 'My own message'));
$validator->fails(); $validator->passes();
$validator->messages()->all();$validator->messages()->all('<p>:message</p>');$validator->messages()->has('name');
Laravel 4: база данных
MySQL
SQLite
MSSQL
PostgreSQL
DB connection
DB connection
Eloquent
Query Builder
Application code
Laravel 4: Query Builder
● where● orWhere● whereBetween● whereNotBetween● whereIn● whereNotIn● whereExists● whereNull
● orderBy● groupBy● distinct● having● skip● take
● first● get● count● max● min● avg● sum● lists● pluck
Laravel 4: Query Builder
// SELECT * FROM users WHERE (role=1 or role=3) AND status=1;DB::table(‘users’)->where(function ($query){
$query->where(‘role’, ‘=’, 1)->orWhere(‘role’, ‘=’, 3);})->where(‘status’, ‘=’, 1)->get();
// SELECT name, email FROM users;DB::table(‘users’)->select(’name’,’email’)->get(); DB::table(‘users’)->select(DB::raw(“name, email”))->get();
// INSERT INTO users (email, name) VALUES ('[email protected]','John'), ('[email protected]','Gary')
DB::table(‘users’)->insert(array(array(‘email’=>’[email protected]’, ‘name‘=>’John’)
array(‘email’=>’[email protected]’, ‘name‘=>’Gary’)));
// UPDATE users SET name=’Lary’ WHERE id=1DB::table(‘users’)->where(‘id’, ‘=’, 1)->update(array(‘name’=>’Lary’));DB::table(‘users’)->where(‘id’, ‘=’, 1)->increment(‘visits’, 1);DB::table(‘users’)->where(‘id’, ‘=’, 1)->decrement(‘visits’, 1);
Laravel 4: Query Builder
// SELECT * FROM users JOIN services ON services.userId = users.id WHERE users.id = 1
DB::table(‘users’)->join(‘services’, ‘services.userId’, ‘=’, ‘users.id’)->where(‘users.id’, ‘=’, 1)->get();
// SELECT * FROM users JOIN services ON services.userId = users.id OR services.parentid = users.id WHERE users.id = 1
DB::table(‘users’)->join(‘services’, function($join) {$join->on(...)->orOn(...);
})->where(‘users.id’, ‘=’, 1)->get();
Laravel 4: ORM
class Users extends Eloquent {
protected $table = “app_users”;public $timestamps = false;protected $fillable = array();protected $guarded = array();
public function role() {return $this->hasOne(‘Role’, ‘id’, ‘profileId’);
}
public function posts() {return $this->hasMany(‘Posts’, ‘userId’);
}}
Laravel 4: CLI● Запуск веб сервера для разработки● Работа с БД - миграция● Вывод список всех определенных роутов● Просмотр логов ● Создание контроллеров● Создание консольных команд● Работа с очередями
Laravel 4: CLI● Вывод строк, выделенных цветом● Запрос ввода данных с консоли● Передача аргументов при запуске команды● Вызов другой команды
Laravel 4: события
// controller methodpublic function createNewUser($email, $pass) { $user = User::create(array(‘email’ => $email, ‘password’ => $pass));
Event::fire(‘user.create’, array($user));}
…// app/start/global.phpEvent::listen(‘user.create’, function ($user) {// send notification email
// added some bonuses// register user for the newsletter
});
Laravel 4: очереди
Queue::push('MessageHandler', array('data' => $data), 'queue_name');Queue::push('MessageHandler@send', array('data' => $data));Queue::later(20,'MessageHandler', array('data' => $data));
class MessageHandler {public function fire($job, $data) {
}
public function send($job, $data) {
}}
● Sync● Beanstalkd● Amazon SQS● IronMq● Redis
Laravel 4: IoC
App::bind(‘UserService’, function () {return new AppUserService();
});
App::singleton(‘UserService’, function () {return new AppUserService();
});
$userService = App::make(‘UserService’);
Laravel 4: IoC
class ClassA {private $classB;
public function __construct(ClassB $classB) {$this->classB = $classB;
}}
class ClassB {
}
$classA = App::make(‘classA’);
Laravel 4: IoC
App::resolving(‘ClassA’, function ($object) {
});
App::resolvingAny(function ($object) {
});
Laravel 4
● Реализовать форму добавления товара● Добавить роут для обработки● Провести валидацию данных перед сохранением в базу
● Сохранить нового товар
Laravel 4
<?php include(‘header.php’);?><form action=”/item/add” method=”post”><div class=”form-group”>
<label class=”col-sm-3 control-label”>Name</label><div class=”col-sm-4”>
<input type=”text” name=”item_name”/></div></div><div class=”form-group”>
<label class=”col-sm-3 control-label”>Cost</label><div class=”col-sm-4”>< input type=”text” name=”item_cost”/></div>
</div></form><?php include(‘footer’); ?>
Laravel 4
<!DOCTYPE html><html><head> <title>{{ trans('config::menu.title') }}</title> <script data-main="/js/main" src="/js/require.js"></script> <link href="/css/bootstrap.min.css" rel="stylesheet"> @yield('custom-style')</head><body>@include('layouts.top')<div class="container-fluid container-min"> @yield('content')</div></body></html>
Laravel 4
Form::macro(‘itemFormRow’, function ($label, $inputType, $inputName) {return ‘<div class=”form-group”><label class=”col-sm-3 control-label”>’.$label.’</label><div class=”col-sm-4”>
<input type=”text” name=”’.$inputName.’”/></div>
</div>’;});
Laravel 4
@extends(‘layout’)
@section(‘content’)
{{ Form::open(array('route'=>'item.add', 'method'=>'post'))}}{{ Form::itemRowField(‘Name’, ‘text’, ‘item_name’)}}{{ Form::itemRowField(‘Cost’, ‘text’, ‘item_cost’)}}{{ Form::close() }}
@stop
Laravel 4
Route::get('/item/', 'App\Item\ItemsController@get');Route::post('/item/', 'App\Item\ItemsController@add');Route::put('/item/', 'App\Item\ItemsController@update');
Route::get('/item/change-property', 'App\Item\ItemsController@formChangeProperty');
Route::post('/item/change-property', 'App\Users\ItemsController@changeProperty');
Laravel 4
Route::group(array( 'prefix'=>'/item/, 'namespace'=>'App\Item\'), function () {
Route::get('/', 'ItemsController@get');Route::post('/',array(
‘as’=>’item.add’,‘uses’=>’'ItemsController@add'’)
);Route::put('/', 'ItemsController@update');
Route::get('/change-property', ItemsController@formChangeProperty'); Route::post('/change-property', 'ItemsController@changeProperty');});
Laravel 4
class Item extends Eloquent {protected $fillable = array(‘name’, ‘cost’);
}
$input = Input::get();$validator = Validator::make( $input, array(‘name’ => 'required|min:5', ‘cost’=>’numeric’));
if($validator->fails()) {throw new Exception(‘Incorrect item data’);
}
return Item::create($input);
Модель
Контроллер
Laravel 4abstract class Validation { protected $rules; protected $input;
public function __construct($input) { $this->input = $input; }
public function validate() { $validator = Validator::make($this->getInput(),
$this->getRules()); if($validator->fails()) { throw new ValidationException($validator); } }
abstract public function getRules();
public function getInput() { return $this->input; }}
Laravel 4class ItemValidationException extends Exception { public function __construct($validator) { $this->message = 'Item data is not valid'; $this->validator = $validator; } public function getErrors() { return $this->validator->messages(); }}
class ItemValidation extends Validation {
public function getRules() { return ['name' => 'required|min:5', 'cost' => 'numeric']; }}
App::error(function (ItemValidationException $e) { $errorResponse = ['message' => $e->getMessage(),'errors' => $e->getErrors() ]; return Response::json($errorResponse, $statusCode = 422);});
Laravel 4$input = Input::get();$validator = Validator::make( $input, array(‘name’ => 'required|min:5', ‘cost’=>’numeric’));
if($validator->fails()) {throw new Exception(‘Incorrect item data’);
}
return Item::create($input);
$itemData = Input::all();App::make('ItemValidation', [$itemData])->validate();return Users::create($itemData);
Что почитать
● http://laravel.com● http://laravel.ru● https://laracasts.com/● http://laravel.io
Вопросы?