Laravel presentation by Arturs Lataks
-
Upload
scandiweb -
Category
Technology
-
view
337 -
download
3
Transcript of 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.
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
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
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
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)
Laravel and ComposerUsing composer in Laravel you can- Add/remove/update packages - Dump autoload file and generate new one- Update laravel version
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...
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”
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)
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);
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.
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
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
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
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
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
- 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
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
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
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
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 }}.
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
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.
Models
- Models are located under app/models directory.
- Simple Product model.
- Will use ‘products’ table unless another defined
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
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
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();
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'));
Laravel migrations
- Interaction with migrations is happening through artisan commands.
- Each migration has two functions up and down to migrate and rollback
Laravel migrations
This is how basic migration looks like
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.
Recap
- Laravel is fast- Flexible- Easy to learn- Has a great documentation- really simple to install- Very popular
???