Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Laravel for Web Artisans

6,557 views

Published on

Presentation slides on used at the TechTalk of Kickstart Maldives. Introduces Laravel PHP framework.

Published in: Software, Technology, Business
  • Login to see the comments

Laravel for Web Artisans

  1. 1. LARAVEL PHP FRAMEWORK FOR WEB ARTISANS
  2. 2. Taylor Otwell Creator of Laravel www.taylorotwell.com @taylorotwell http://taylorotwell.com/on-community/
  3. 3. http://www.github.com/laravel/laravel V 4.2.X Current Release
  4. 4. Google Trends from 2004 to current
  5. 5. <? WHY ?>
  6. 6. Easy to Learn
  7. 7. Ready For Tomorrow
  8. 8. Great Community
  9. 9. Composer Powered www.getcomposer.org Dependency Manager for PHP
  10. 10. Eloquent ORM
  11. 11. Easy for TDD FAIL PASS REFACTOR
  12. 12. INSTALLATION It’s too easy, I don’t have to tell you.
  13. 13. IoC Inverse of Control IlluminateContainerContainer
  14. 14. Wikipedia In software engineering, inversion of control describes a design in which custom-written portions of a computer program receive the flow of control from a generic, reusable library “what you get when your program make a call” “Removing dependency from the code”
  15. 15. Simplifying Dependency Injection $object = new SomeClass($dependency1, $dependency2); $object = App::make(‘SomeClass’);
  16. 16. Hard-coded source dependency public function sendEmail() { $mailer = new Mailer; $mailer->send(); } public function sendEmail() { $mailer = App::make(‘Mailer’); $mailer->send(); } IoC Resolution
  17. 17. Telling IoC what we need $Bar = App::make(‘Bar’); // new Bar; App::bind(‘Bar’, ‘MockBar’); $Bar = App::make(‘Bar’); // new MockBar;
  18. 18. Simple ways to bind to the IoC App::bind(‘SomeClass’, function() { return new Foo; }); $fooObject = new Foo; $object = App::bind(‘SomeClass’, $fooObject); App::bind(‘SomeClass’, ‘Foo’);
  19. 19. Singleton Dependencies $object = App::singleton(‘CurrentUser’, function() { $auth = App::make(‘Auth’); return $auth->user(); // returns user object });
  20. 20. Automatic Dependency Resolution class EmailService { public function __construct(Mailer $mailer) { $this->mailer = $mailer; } public function sendEmail() { $this->mailer->send(); } } $EmailService = App::make(‘EmailService’);
  21. 21. Service Providers
  22. 22. Service Providers use IlluminateSupportServiceProvider; class ContentServiceProvider extends ServiceProvider { public function register() { $this->app->bind(‘PostInterface’, ‘MyNameSpacePost’); } } App::register(‘ContentServiceProvider’); // Registering at Runtime
  23. 23. Laravel Facades Illuminate/Support/Facades/Facade
  24. 24. What is Facade In Laravel Context Facade is a class that provide access to an object registered in the IoC container. Facade Class IoC Container Object A cades enable you to hide complex interface behind a simple one.
  25. 25. What is happening? Illuminate/Support/Facades/Route Route::get(‘/’, ‘HomeController@getIndex’); $app->make(‘router’)->get(‘/’, ‘HomeController@getIndex’); Illuminate/Routing/Router
  26. 26. Facades in Laravel Illuminate/Support/Facades/ App Artisan Auth Blade Cache Config Cookie Crypt DB Event File Form Hash HTML Input Lang Log Mail Paginator Password Queue Redirect Redis Request Response Route Schema ViewSession SSH URL Validator Illuminate/Foundation/Application
  27. 27. Eloquent Talking to your data IlluminateDatabaseEloquentModel
  28. 28. $result = mysql_query(“SELECT * FROM `users`”); How you query in plain PHP 5.4 or less (deprecated) $mysqli = new mysqli(“localhost”, “user”,”password”,”database”); $result = $mysqli->query(“SELECT * FROM `users` “); How you query in plain PHP 5.5 or above User::all(); In Laravel 4, does the same query
  29. 29. User::all(); DB::table(‘users’)->get(); IlluminateDatabaseQueryBuilder What happens when you use Eloquent ORM
  30. 30. Create, Read, Update, Delete Post::create($data); Post::find($id); Post::find($id)->update($data); Post::delete($id);
  31. 31. Eloquent Model Class class Post extends Eloquent { public function comments() { return $this->hasMany(‘Comment’); } public function author() { return $this->belongsTo(‘User’); } public function scopePublished($q) { return $q->where(‘publish’,’=‘,1); } }
  32. 32. Eloquent Model Class class Post extends Eloquent { public function comments() { return $this->hasMany(‘Comment’); } public function author() { return $this->belongsTo(‘User’); } public function scopePublished($q) { return $q->where(‘publish’,’=‘,1); } }
  33. 33. $post = Post::find($id); $author = post->author; // get the author object Get Post’s Author Object $posts = Post::with(‘author’)->get(); Get Posts including Authors
  34. 34. Get Post Comments Approved $post = Post::find($id); $comments = $post->comments() ->where(‘approved’, true)->get();
  35. 35. Model with Query Scope $published_posts = Post::published()->get(); // gets all posts published $published_posts = Post::where(‘publish’, ‘=‘, true)->get(); // gets all posts published
  36. 36. Query Scope Example class Post extends Eloquent { public function comments() { return $this->hasMany(‘Comment’); } public function author() { return $this->belongsTo(‘User’); } public function scopePublished($q) { return $q->where(‘publish’,’=‘,1); } }
  37. 37. Eloquent Relations
  38. 38. Eloquent Relationship One to One (hasOne) class User $this->hasOne(‘Profile’, ‘user_id’); function Profile() Users pK: id username email Profile pk: id fK: user_id url
  39. 39. class Post $this-> hasMany(‘Comment’); function comments() Posts pK: id title user_id Comments pk: id fK: post_id user_id Eloquent Relationship One to Many (hasMany)
  40. 40. class User $this-> belongsToMany(‘Group’); function groups() Users pK: id username email Groups pk: id Name Group_User user_id group_id Eloquent Relationship Many to Many (belongsToMany)
  41. 41. class Country $this-> hasManyThrough(‘User’); function posts() Countries pK: id name code Posts pk: id user_id title body Users pK: id country_id username email Eloquent Relationship One to Many through (hasManyThrough)
  42. 42. Eloquent Relationship Polymorphic Association $user->image; $movie->image; class Movie $this-> morphMany(‘Photo’, ‘imageable); function image() Profile pK: id user_id preferences Photos pk: id file_path imageable_id imageable_type Movie pK: id title released class Photo $this-> morphTo(); function imageable() class Profile $this-> morphMany(‘Photo’, ‘imageable); function image()
  43. 43. Eloquent Relationship Many to Many Polymorphic Association $movie->tags; $post->tags; Posts pK: id title body Taggables tag_id taggable_id taggable_type Movie pK: id title released class Movie $this-> morphToMany(‘Tag’, ‘Taggable’); function tags() Tags pk: id name class Post $this-> morphToMany(‘Tag’, ‘Taggable’); function tags() class Tag $this-> morphedByMany (‘Post’, ‘Taggable’); function posts() $this-> morphedByMany (‘Movie’, ‘Taggable’); function movies()
  44. 44. Underneath Eloquent Model Query Builder DB::table(‘users’)->get(); DB::table(‘users’)->where(‘email’, ‘raftalks@gmail.com’)->first(); DB::table(‘users’)->where(‘votes’, ‘>’, 100) ->orWhere(‘votebox’, ‘A’)->get(); IlluminateDatabaseQueryBuilder
  45. 45. Complex Queries via Query Builder DB::table(‘users’) ->join(‘contacts’, function($join) { $join->on(‘users.id’, ‘=‘, ‘contacts.user_id’) ->whereNotNull(‘contacts.mobile_number’); }) ->leftJoin(‘submissions’,’users.id’, ‘=‘, ‘submissions.user_id’) ->whereExists(function($query) { $query->select(DB::raw(1))->from(‘reviews’) ->whereRaw(‘reviews.user_id = users.id’); }) ->whereYear(‘users.joined_date’, ‘>’, 2010) ->get(); Get all users joined after year 2010 having over 1000 visits and having submitted reviews. Only select users with their contacts having mobile numbers and include if they have any content submitted.
  46. 46. Find out remaining 70% of Eloquent Features from the documentation
  47. 47. Routing Wolf
  48. 48. Multiple Routing Paradigms 1. route to closures 2. route to controller actions 3. route to RESTful controllers 4. route to resource
  49. 49. Routing to Closure Route::get(‘techtalks’, function() { return “<h1> Welcome </h1>“; }); Route::post(‘techtalks’, function() { }); Route::put(‘techtalks/{id}’, function($id) { }); Route::delete(‘techtalks/{id}’, function($id) { }); Route::any(‘techtalks’, function() { });
  50. 50. Route Groups and Filters Route::group([‘prefix’=>’settings’, ‘before’=>’auth’], function() { Route::get(‘users’, function() { // get a post by id }); }); Route::filter(‘auth’, function() { if (Auth::guest()) return Redirect::guest('login'); });
  51. 51. Subdomain Routing // Registering sub-domain routes Route::group([‘domain’ =>’{account}.fihaara.com’], function() { Route::get(‘/’, function($account) { return “welcome to “ . $account; }); });
  52. 52. Routing to a Controller Action class HomePageController extends BaseController { public function home() { return “welcome to home page”; } } Route::get(‘/‘, ‘HomePageController@home’);
  53. 53. class TechTalksController extends Controller { public function getIndex() {} /talks public function getTalkerProfile($id) {}/talks/talker-profile/1 public function getTalk($id) {} /talks/talk/1 public function postTalk(){} /talks/talk public function putTalk(){} /talks/talk public function deleteTalk($id){} /talks/talk/1 } Routing to RESTful Controller Route::controller(‘talks’, ‘TechTalksController’); Public method must be prefixed with an HTTP verb
  54. 54. class PostsController extends Controller { public function index() {} // posts GET public function create() {} // posts/create GET public function store() {} // posts POST public function show($id) {} // posts/{id} GET public function edit($id) {} // posts/{id}/edit GET public function update() {} // posts/{id} PUT public function destroy() {} // posts/{id} DELETE … Routing to Resource Controller Route::resource(‘posts’, ‘PostsController’);
  55. 55. Other Cool Features
  56. 56. Authentication $credentials = [‘username’=> ‘raftalks’, ‘password’ => ‘secret’]; if (Auth::attempt($credentals) === false) { return Redirect::to(‘login-error’); } if (Auth::check() === false) { return Redirect::to(‘login’); } Check if user is authenticated
  57. 57. Localization App::setLocale(‘dv’); echo Lang::get(‘news.world_news’); // out puts “‫ދ‬ު ‫ނ‬ި ‫ޔ‬ޭ ‫ގ‬ެ ‫ޚ‬ަ ‫ބ‬ަ ‫ރ‬ު ” echo Trans(‘news.world_news’); Basic Usage return array( “world_news” => “‫ދ‬ު ‫ނ‬ި ‫ޔ‬ޭ ‫ގ‬ެ ‫ޚ‬ަ ‫ބ‬ަ ‫ރ‬ު ”, “news” => “‫ޚ‬ަ ‫ބ‬ަ ‫ރ‬ު ”, … Lang File FILE PATH: /app /lang /dv news.php
  58. 58. Artisan CLI Laravel Provides Artisan Commands for Rapid Development You can develop custom Artisan commands for a package or an application
  59. 59. Creating DB Migration php artisan migrate:make create_users_table --create=users class Create_Users_table extends Migration { public function up() { Schema::create(‘users’, function(Blueprint $table) { $table->increments(‘id’); $table->string(‘username’, 50); $table->string(‘password’, 200); }); }, public function down() { Schema::drop(‘users’); } }
  60. 60. Seeding into your DB class DefaultAdminUserSeeder extends Seeder { public function run() { DB::table(‘users’)->delete(); // truncates the table data User::create([ ‘username’=>’admin’, ‘password’=> Hash::make(‘password’) ]); } }
  61. 61. Events Event::fire(‘news.created’, $post); Event::listen(‘news.created’,function($post) { UserPostCounter::increment(‘posts’, $post->user_id); });
  62. 62. Mail Mail::send(‘emails.welcome’, $data, function($message) use($user) { $message->to($user->email, $user->name) ->subject(‘Welcome’); }); uses SwiftMailer Library or use API drivers for Mailgun or Mandrill
  63. 63. Queues Beanstalkd Amazon SQS IronMQ Redis Synchronous (for lcoal use) Queue::push('SendEmail', [‘message' => $message]); php artisan queue:listen
  64. 64. Remote SSH SSH::run([ ‘cd /var/www’, ‘git pull origin master’ ]);
  65. 65. Laravel Homestead ng Vagrant, we now have easy way to simply manage virtual mac Included Softwares • Ubuntu 14.04 • PHP 5.5 • Nginx • MySQL • Postgres • Node (with Bower, Grunt, Gulp) • Redis • Memcached • Beanstalkd • Laravel Envoy • Fabric + HipChat Extension
  66. 66. Sign Up -> Add Your Cloud’s API Key -> Serve Happiness forge.laravel.com
  67. 67. Meet the community @ IRC Channel: #laravel Server: irc.freenode.net Port: 6667
  68. 68. Next Laracon laracon.eu/2014
  69. 69. Laravel Maldives Group Wouldn’t it be awesome for us to have our own Laracons Feel free to get in touch with me if you are interested. My Emails: 7909000@gmail.com / raftalks@gmail.com
  70. 70. ???
  71. 71. Sleep Well :)

×