Top Banner
34

Laravel presentation by Arturs Lataks

Jul 15, 2015

Download

Technology

scandiweb
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Laravel presentation by Arturs Lataks
Page 2: Laravel presentation by Arturs Lataks

What’s Laravel?

THE PHP FRAMEWORK FOR WEB ARTISANS.PHP THAT DOESN'T HURT. CODE HAPPY & ENJOY THE FRESH AIR.

Page 3: Laravel presentation by Arturs Lataks

Where to start from?

Laravel is very flexible framework. There are at least 3 options how to create new project:- via laravel installer- via composer- clone from github

Page 4: Laravel presentation by Arturs Lataks

Via Laravel installerThis will download laravel installer via composer- composer global require "laravel/installer=~1.1"

When installer added this simple command will create app- laravel new <app name>

* Do not forget to add ~/.composer/vendor/bin to your PATH variable in ~/.bashrc

Page 5: Laravel presentation by Arturs Lataks

Other options

Via composer- composer create-project laravel/laravel your-project-name

Get from GitHub- https://github.com/laravel/laravel- And then in the project dir run “composer install” to get all needed

packages

Page 6: Laravel presentation by Arturs Lataks

Development environment

Laravel keeps index.php file under public directory meaning that when setting up virtual host for app you need DocumentRoot to point to public directory.

Any wild guesses why?(please don’t use retarded http://localhost/mycoolproject/public)

Page 7: Laravel presentation by Arturs Lataks

Laravel and ComposerUsing composer in Laravel you can- Add/remove/update packages - Dump autoload file and generate new one- Update laravel version

Page 8: Laravel presentation by Arturs Lataks

Laravel directory structureThe app directory, as you might expect, contains the core code of your application.The bootstrap folder contains a few files that bootstrap the framework and configure autoloading.The app/config directory, as the name implies, contains all of your application's configuration files.The app/database folder contains your database migration and seeds.The public directory contains the front controller and your assets (images, JavaScript, CSS, etc.).The app/storage directory contains compiled Blade templates, file based sessions, file caches, and other files generated by the framework.The tests directory contains your automated tests.The vendor directory contains your Composer dependencies.The app/model directory contains your modelThe app/controllers directory contains your model...

Page 9: Laravel presentation by Arturs Lataks

Magic Artisan- Is located Laravel project root directory- Basically is a php script which performs all actions in

Laravel for example:- Manage migrations- Check application routes- Clear app cache- Create Artisan commands(??)- Run database seeds

Full list is available with “php artisan list”

Page 10: Laravel presentation by Arturs Lataks

Artisan commandsArtisan commands usually are some scripts launched from command line or with cron. For example you need to have daily export of your orders - write a command and run it with cron.- They accept options and

arguments- Have pretty output if

needed- Interactive (can ask

password/question)

Page 11: Laravel presentation by Arturs Lataks

Laravel ConfigLaravel uses config files with arrays in it to store different configurations. database.php ->

Location: app/config

To get config value simply follow dot notation Config::get(‘<filename>.key1.key2.key3’);Can also pass default value on not found Config::get(‘key’, 123);

Page 12: Laravel presentation by Arturs Lataks

Laravel environmentsAre stored in app/bootstrap/start.php How it can look:

$env = $app->detectEnvironment(array(‘local’ => array(‘<my local hostname>’, ‘<someones other>’),‘live’ => array(‘<live hostname>’),‘arturs_local’ => array(‘<arturs local hostname>’),

));

Are used for configuration files, meaning that each environment can have it’s own config.

Page 13: Laravel presentation by Arturs Lataks

So basically it means that under app/config directory you will have more directories with environment names.

In overrided files you should put only those variables which need to be overridden.

Laravel environments

Page 14: Laravel presentation by Arturs Lataks

Laravel actively uses php namespaces to keep classnames short and keep possibility to use same class names for different components.

I would suggest everyone to use namespaces too. For example all Admin functionality under Admin namespace.

Laravel and namespaces

Page 15: Laravel presentation by Arturs Lataks

So Laravel is MVC framework meaning we have folder for controllers, views and models by default, no need to create them.

Guess there’s no need to explain MVC pattern.

Laravel MVC

Page 16: Laravel presentation by Arturs Lataks

Defining Laravel routes is dead simple and there are lots of ways to do it. All routes are defined in app/routes.php

- Simplest get route: Route::get('/', function() { return 'Hello World'; });

- More advanced named route (still get method): Route::get('user/profile', array('as' => 'profile', function() { // }));

Laravel Routes

Page 17: Laravel presentation by Arturs Lataks

In the previous example you had to define every route by hand. Isn’t very convenient though. So you can define controller prefixes and let Laravel decide which action to use. So in routes.php Route::controller('user', 'UserController'); Route::controller('product', 'ProductController');And in UserController you will have methods like “getLogout”, “postLogin”, “getLogin” where post|get is type of request and logout is the second part of request url : http://example.com/user/login

Laravel Routes

Page 18: Laravel presentation by Arturs Lataks

- Filters are run before or after some controller action

- Are defined in app/filters.php- There are global App::before and App::after

filters.- Filters can be binded to multiple controllers

Laravel Filters

Page 19: Laravel presentation by Arturs Lataks

There’s one main Controller class which all controllers should extend. By default Laravel has BaseController (extends from Controller) and HomeController (extends from BaseController)

Basic example from default Laravel installation:

Laravel controllers

Page 20: Laravel presentation by Arturs Lataks

More advanced example.

Laravel controllers

Responds only to get method and returns rendered view

Responds to post method, and returns redirect to next logical action

Page 21: Laravel presentation by Arturs Lataks

Talking about Views

- All views are located in app/views directory - Can be separated in subdirectories- Can be both blade or simple php files

It is recommended to use balde template engine since it is very convenient and helps to eliminate random logic blocks in views

Page 22: Laravel presentation by Arturs Lataks

Insights in blade

Echo data simple way:Hello, {{{ $name }}}.The current UNIX timestamp is {{{ time() }}}.

Hello, {{{ $name or ‘John Doe’ }}} gets rendered as <?php echo isset($name) ? $name : ‘John Doe’ ?>

Don’t escape data with htmlentities:Hello, {{ $name }}.

Page 23: Laravel presentation by Arturs Lataks

Insights in blade

Comments:{{-- Comment visible only in blade file --}}

Loops: @forelse($users as $user) <li>{{ $user->name }}</li>@empty <p>No users</p>@endforelse

Conditions: @if (count($records) === 1)

I have one record!@elseif (count($records) > 1) I have multiple records!@else I don't have any records!@endif

@unless (Auth::check()) You are not signed in.@endunless

Page 24: Laravel presentation by Arturs Lataks

Return view from controller

Views are also accessed by dot notation from view directory. So if we have app/views/user/profile.blade.php then to make this view View::make(‘user.profile’, $data) Where data is key value array with data used in template.

Page 25: Laravel presentation by Arturs Lataks

Models

- Models are located under app/models directory.

- Simple Product model.

- Will use ‘products’ table unless another defined

Page 26: Laravel presentation by Arturs Lataks

Laravel ORM

Why is it good?- Has a lot of useful methods- Is very flexible- Has built in safe delete functionality- Has built in Relationship functionality- Has option to define scopes

Page 27: Laravel presentation by Arturs Lataks

Laravel ORM- Models can have relations defined in

them for easier access to properties.- $product->category in this case will

return Category model object where this product belongs. How?

Laravel assumes you have category_id in your products table, so when you call $product->category query SELECT * FROM ‘categories’ where id = ‘?’ is performed. Of course you can define different relation fields

Page 28: Laravel presentation by Arturs Lataks

Laravel ORM

Defining scope:class User extends Eloquent {

public function scopePopular($query) { return $query->where('votes', '>', 100); }

public function scopeWomen($query) { return $query->whereGender('W'); }

}

Using scope:$users = User::popular() ->women() ->orderBy('created_at') ->get();

Page 29: Laravel presentation by Arturs Lataks

Laravel ORM

Cool methods:

Basically Laravels ORM has function for anything

// Retrieve the user by the attributes, or create it if it doesn't exist...$user = User::firstOrCreate(array('name' => 'John'));

// Retrieve the user by the attributes, or instantiate a new instance...$user = User::firstOrNew(array('name' => 'John'));

Page 30: Laravel presentation by Arturs Lataks

Laravel migrations

- Interaction with migrations is happening through artisan commands.

- Each migration has two functions up and down to migrate and rollback

Page 31: Laravel presentation by Arturs Lataks

Laravel migrations

This is how basic migration looks like

Page 32: Laravel presentation by Arturs Lataks

DB seeds

Seeds are used to insert predefined data in tables so there is something to start from for example on development environment we can create test users, test products and so on.

Page 33: Laravel presentation by Arturs Lataks

Recap

- Laravel is fast- Flexible- Easy to learn- Has a great documentation- really simple to install- Very popular

Page 34: Laravel presentation by Arturs Lataks

???