Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Laravel 4 Fundamentals

Laravel 4 Fundamentals

Laravel is a web application framework with expressive, elegant syntax. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching. Lately, Laravel 4 has gained great popularity and is the most popular PHP project on GitHub with over 600,000 downloads. Part of the reason for this popularity is Laravel’s friendly & vibrant community which keeps growing every day.

Angel Ramirez

March 19, 2014
Tweet

More Decks by Angel Ramirez

Other Decks in Programming

Transcript

  1. WHO AM I ? • CEO at Cuemby. • Full

    stack developer. • Math, challenges and new technologies lover. LARAVEL FANBOY @angel_cuemby cuemby [email protected] https://joind.in/10838
  2. TELL ME ABOUT LARAVEL • Is framework created by Taylor

    Otwell. • Is a web application framework with expressive, elegant syntax. • Attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching. • Is build based on the best of others frameworks out there like Rails, ASP .NET and Sinatra. Users::where(‘name’, ‘=‘, ‘Angel’)->first(); //Hashing password, using build in API
 Hash::make(‘secrect-password’);
 //Authenticating user by email and password
 Auth::attempt(array(‘email’ => $email, ‘password’ => $password
 ));
 //Accessing to our Session
 Session::get('key', function() { 
 return 'default'; 
 });
  3. FACADES ISN'T MAGIC ! ITS A PATTERN /* Calling a

    Service Provider trough a facade */
 Cart::addProduct($product); HOW THIS WORKS ? /* Assume we have a class Cart at ACME/Classes/Cart.php */
 class Cart {
 public function addProduct($product){
 . . .
 }
 }
  4. /* Creating a Facade */
 class Cart extends Facade {


    protected static function getFacadeAccessor(){
 return ‘cart’;
 }
 }
 /* Registering Facades on app/config/app.php */
 ‘Cart’ => ‘ACME\Facades\Cart’ FACADES ISN'T MAGIC ! ITS A PATTERN /* Creating a Service Provider */
 use Illuminate\Support\ServiceProvider;
 
 class CartServiceProvider extends ServiceProvider{
 public function register(){
 $this->app->bind(‘cart’, function(){
 return new Cart;
 });
 }
 }
 
 /* Registering a service provider on app/config/app.php */
 ACME\ServiceProviders\Cart,
  5. OK AND HOW DO I START ? Installation - Config

    Routes - Views - Controllers Models - Eloquent - Migrations - Seeding Blade - Master Pages - Forms - Validations RESTful, Resource and Filters - Controllers Sessions - Security - Queues - Mail BASIC MVC BASIC LARAVEL IoContainer Service Provider Facade :( Magic ? Events Testing Package Development
  6. FIRST THINGS FIRST composer create-project laravel/laravel app-name php artisan serve

    EASY RIGHT ? RUN BUILT IN SERVER YOUR FIRST ROUTE ! AND A VIEW COME ON GUYS GIVE A WAAOOO !!! Route::get(‘/users’, function(){
 return ‘Hello to users’; }); Route::get(‘/’, function(){
 return View::make(‘home’); });
  7. ROUTES Route::get(‘/‘, function(){ // use post, put, patch or any

    other verb,
 return ‘Hello World’; Route::match(‘GET’, ‘POST’, . . .);
 }); Route::get(‘user/{id}’, array(‘https’, function(){
 return ‘User’ . $id; //use {id?} for optional
 }); Route::get(‘/dashboard‘, array(‘before’ => ‘auth.basic’, function(){
 return ‘Only accessible via https’;
 }); Route::group(array(‘prefix’ => ‘api’, ‘before’ => ‘auth.basic’, function(){
 Route::get(
 ‘user/{id}/contacts’, 
 array(‘as’ => ‘profile’, ‘uses’ => ‘UserController@showContacts’)
 );
 });
  8. FILTERS Route::filter('auth.basic', function() { return Auth::basic(); }); Route::filter('csrf', function() {

    if (Session::token() != Input::get('_token')) { throw new Illuminate\Session\TokenMismatchException; } }); App::before(function($request){
 // }); ! App::after(function($request, $response){
 // });
  9. MODELS A model is a layer representation of what you

    have on your data*. app/models/Order.php. use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableInterface; ! class Order extends Eloquent {
 protected $table = ‘orders’; protected $guarded = array(‘id’, ‘coCode’); protected $fillable = array(‘shippingAddress’, ‘pickupStore’); protected $hidden = array(‘id’, ‘coCode’);
 protected $softDelete = true; protected $timestamps = false;
 
 public function setShippingAddressAttribute($value){}
 public function getPickupStoreAttribute(){};
 }
  10. MODELS RELATIONS class Order extends Eloquent {
 … public function

    cart(){ 
 $this->belongsTo(‘Cart’, ‘foreign_key’, ‘local_key’); // One To One inverse definition. } public function items(){ $this->hasMany(‘Item’, ‘foreign_key’, ‘local_key’); // One To Many inverse definition. } public function addresses(){
 $this->belongsToMany(‘Address’, ‘order_address’, ‘local_key’, ‘foreign_key); // Many To Many inverse definition. }
 } class Cart extends Eloquent {
 … public function order(){ 
 $this->hasOne(‘Order’, ‘local_key’, ‘parent_key’); // One To One.
 }
 } class Items extends Eloquent {
 … public function order(){ 
 $this->belongsTo(‘Order’, ‘local_key’, ‘parent_key’); // One To One.
 }
 }
  11. MODELS LIFECYCLE Eloquent models fire several events, allowing you to

    hook into various points in the model's lifecycle using the following methods: creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored. class Order extends Eloquent {
 .. ..
 
 public function setShippingAddressAttribute($value){}
 public function getPickupStoreAttribute(){}; ! public static function boot(){
 parent::boot();
 Order::creating(function($order){ if (! $order->isValid()) return false; });
 }
 }
  12. MODELS SCOPES Scopes allow you to easily re-use query logic

    in your models. To define a scope, simply prefix a model method with scope. class Order extends Eloquent {
 .. .. ! public function scopeYesterday($query){ return $query->whereCreatedAt(‘2014/17/03’);
 } ! public function scopeZipCode($query, $zipCode){ return $query->where(‘zip_code’, ‘=‘, $zipCode);
 }
 } ! ! $orders = Order::yesterday()->zipCode(33160)->orderBy(‘created_at’)->get();
  13. ELOQUENT CRUD Scopes allow you to easily re-use query logic

    in your models. To define a scope, simply prefix a model method with scope. // Creating $order = new Order; $order->pickup_store = ‘Best Buy’; $order = Order::create(array(‘pickup_store’ => ‘Best Buy’));
 // Reading
 $order = Order::find(1); $order = Order::where(‘pickup_store’, ‘=‘, ‘Best Buy’);
 
 // Updating $order = Order::find(1); $order->pickup_store = ‘Tiger Direct’; $rows = Order::where(‘zip_code’, '=', 33160)->update(array('status' => ‘ready’)); ! // Deleting $order = Order::find(1); $order->delete(); $rows = Order::where(‘created_at’, '<', ‘2005/01/01’)->delete();
  14. ELOQUENT QUERYING RELATIONS // Simple access $orders = Order::has(‘items’)->get(); $orders

    = Order::has(‘items’, ‘>=’, ‘5’)->get();
 // Using whereHas $orders = Order::whereHas('items', function($q){ $q->where('title', 'like', 'foo%'); })->get();
 
 // Dynamic Properties $order = Order::find(1); $order->cart->created_at; $order->items; ! // Efficiency $users = User::with(array('posts' => function($query){ $query->orderBy('created_at', 'desc') }))->get(); ! ! // Lazy Eager Loading $order = Order::find(1); $order->load(‘items’, ‘addresses’);
  15. MIGRATIONS COMMANDS Migrations are a type of version control for

    your database. They allow a team to modify the database schema and stay up to date on the current schema state. php artisan migrate:make create_users_table —-create=users --path=app/migrations ! php artisan migrate:make add_votes_to_user_table --table=users
 
 php artisan migrate // Running migrations ! php artisan migrate:rollback // Rolling back last migration ! php artisan migrate:reset // Rollback all migrations ! php artisan migrate:refresh --seed // Rollback all and seed
  16. SCHEMA BUILDER The Laravel Schema class provides a database agnostic

    way of manipulating tables. It works well with all of the databases supported by Laravel, and has a unified API across all of these systems. use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; ! class CreatePasswordRemindersTable extends Migration { ! public function up() { Schema::create('password_reminders', function(Blueprint $table) { $table->string('email')->index(); $table->string('token')->index(); $table->timestamp('created_at'); }); } ! public function down() { Schema::drop('password_reminders'); } }
  17. SEEDERS Laravel also includes a simple way to seed your

    database with test data using seed classes. All seed classes are stored in app/database/seeds. class DatabaseSeeder extends Seeder { ! public function run() { $this->call('UserTableSeeder'); ! $this->command->info('User table seeded!'); } ! } ! class UserTableSeeder extends Seeder { ! public function run() { DB::table('users')->delete(); ! User::create(array('email' => '[email protected]')); } ! }
  18. BLADE Blade is a simple, yet powerful templating engine provided

    with Laravel. Unlike controller layouts, Blade is driven by template inheritance and sections. <!-- Stored in app/views/layouts/ master.blade.php --> ! <html> <body> @section('sidebar') This is the master sidebar. @show ! <div class="container"> @yield('content') </div> </body> </html> <!-- Stored in app/views/ home.blade.php --> ! @extends('layouts.master') ! @section('sidebar') @parent ! <p>This is appended to the master sidebar.</p> @stop ! @section('content') <p>This is my body content.</p> @stop
  19. FORMS // Simple form {{ Form::open(array('url' => ‘order/create’, ‘method’ =>

    ‘post’)) }} // {{ Form::close() }} // Tight a form to one controller method {{ Form::open(array(‘action’ => array('Controller@method', $user->id))) }} // Binding a form to a model {{ Form::model($user, array('route' => array('user.update', $user->id))) }} // Creating macros Form::macro('myField', function() { return '<input type="awesome">'; });
  20. VALIDATIONS $validator = Validator::make( array( 'name' => 'Dayle', 'password' =>

    'lamepassword', 'email' => '[email protected]' ), array( 'name' => 'required', 'password' => 'required|min:8', 'email' => 'required|email|unique:users' ) ); if ($validator->fails()) { $messages = $validator->messages(); }
  21. BASIC CONTROLLERS class UserController extends BaseController { ! public function

    showProfile($id) { $user = User::find($id); ! return View::make('user.profile', array('user' => $user)); } ! } Route::get('user/{id}', 'UserController@showProfile'); Controllers are typically stored in the app/controllers directory, and this directory is registered in the classmap option of your composer.json file by default.
  22. RESTFUL CONTROLLERS class UserController extends BaseController { ! public function

    getIndex() { // } ! public function postProfile() { // } } Route::controller('users', 'UserController'); Laravel allows you to easily define a single route to handle every action in a controller using simple, REST naming conventions. First, define the route using the Route::controller method.
  23. RESOURCE CONTROLLERS Route::resource('photo', 'UserController'); Using the controller:make command via the

    Artisan CLI and the Route::resource method, we can quickly create a resource controller. php artisan controller:make PhotoController
  24. FILTER CONTROLLERS class UserController extends BaseController { ! public function

    __construct() { $this->beforeFilter('auth', array('except' => 'getLogin')); ! $this->beforeFilter('csrf', array('on' => 'post')); ! $this->afterFilter('log', array('only' => array('fooAction', 'barAction'))); } ! }
  25. LET’S PLAY WITH SESSIONS - php artisan session:table - composer

    dump-autoload - php artisan migrate Laravel ships with a variety of session back-ends available for use through a clean, unified API. Support for popular back-ends such as Memcached, Redis, and databases is included out of the box. Session::push('user.teams', 'developers'); $value = Session::get('key', function() { return 'default'; }); $data = Session::all(); Session::forget('key'); Session::flush(); Session::regenerate();
  26. AND SECURITY ? Laravel aims to make implementing authentication very

    simple. In fact, almost everything is configured for you out of the box. $password = Hash::make('secret'); if (Hash::check('secret', $hashedPassword)){ // some code here } if (Auth::attempt(array('email' => $email, 'password' => $password), true)) { return Redirect::intended('dashboard'); } if (Auth::once($credentials)){ // some code here } Auth::logout();
  27. QUEUES - php artisan queue:listen The Laravel Queue component provides

    a unified API across a variety of different queue services. Queues allow you to defer the processing of a time consuming task, such as sending an e-mail, until a later time, thus drastically speeding up the web requests to your application. Queue::push('SendEmail', array('message' => $message), ‘emails’); class SendEmail { public function fire($job, $data) { // $job->delete(); $job->release(); } }
  28. MAILS Laravel provides a clean, simple API over the popular

    SwiftMailer library. The mail configuration file is app/config/mail.php, and contains options allowing you to change your SMTP host, port, and credentials, as well as set a global from address for all messages delivered by the library. Mail::send('emails.welcome', $data, function($message){ ! $message->from('[email protected]', 'Laravel'); $message->to('[email protected]', 'John Smith’)->subject('Welcome!'); $message->attach($pathToFile, array('as' => $display, 'mime' => $mime)); }); Mail::queue('emails.welcome', $data, function($message) { $message->to('[email protected]', 'John Smith')->subject('Welcome!'); });
  29. THEN WHAT I NEED TO BE A LARAVEL MASTER ?

    PRACTICE ! PRACTICE ! PRACTICE ! AND SEE ADVANCE TOPICS LIKE: IOCONTAINER SERVICE PROVIDER FACADES EVENTS UNIT TESTING CORE PACKAGE DEVELOPMENT
  30. • CODE BRIGHT BY DAYLE REES • LARAVEL TESTING DECODED

    BY JEFFREY WAY • LARAVEL: FROM APPRENTICE TO ARTISAN BY TAYLOR OTWELL • IMPLEMENTING LARAVEL BY CHRIS FIDAO • GETTING STUFF DONE WITH LARAVEL 4 BY CHUCK HEINTZELMAN • LARAVEL 4 COOKBOOK BY CHRISTOPHER PITT • LARAVEL IN ACTION BY MAKS SURGUY • LARACASTS.COM BY JEFFREY WAY REFERENCES