This document provides an overview of key concepts in the Laravel PHP framework, including Lumen, middleware, dependency injection, filesystem/cloud storage, queues, task scheduling, databases, Eloquent ORM, and the LUCID architecture pattern. It discusses how Laravel supports middleware, dependency injection, filesystem abstraction, queueing, scheduling tasks, querying databases, migrations, seeding, and the Eloquent ORM. It also summarizes the LUCID architecture designed by Vinelab to improve code quality by defining features, jobs, services, and domains.
4. Middleware
HTTP middleware provide a convenient mechanism for filtering
HTTP requests entering your application.
● Maintenance
● Authentication
● CSRF protection
MeetingMogul
Validate twilio requests (Header Signature)
5. <?php
namespace AppHttpMiddleware;
use Log;
use Closure;
use AppRepositoriesTwilioAccountTwilioAccountRepositoryInterface;
class ValidateTwilioRequestMiddleware
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!$this->validateRequest($request)) {
throw new SymfonyComponentHttpKernelExceptionUnauthorizedHttpException('Twilio', 'You are not authorized to access this
resource.');
}
return $next($request);
}
}
6. Dependency Injection
Laravel provides a convenient way to inject dependencies
seemlessly.
<?php
namespace Database;
class Database
{
protected $adapter;
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
}
}
7. <?php
namespace AppApiv1Controllers;
use AppApiTransformersMessageStatusTransformer;
use AppRepositoriesUserUserRepositoryInterface;
/**
* Message Resource
*
* @Resource("Message", uri="/messages")
*/
class MessageController extends BaseController
{
protected $userRepo;
public function __construct(Request $request, UserRepositoryInterface $userRepo)
{
parent::__construct($request);
$this->userRepo = $userRepo;
}
protected function setMessagingStatus(Request $request)
{
$this->userRepo->createOrUpdateProfile($this->auth->user(), $request->all());
return (['message' => 'Message Status updated successfully.']);
}
}
9. Cloud Storage
Laravel provides a powerful filesystem abstraction. It
provides simple to use drivers for working with Local
filesystems, Amazon S3 and Rackspace Cloud Storage. Even
better, it's amazingly simple to switch between these
storage options as the API remains the same for each system.
10. Cloud Storage
public function updateAvatar(Request $request, $id)
{
$user = User::findOrFail($id);
Storage::put(
'avatars/'.$user->id,
file_get_contents($request->file('avatar')->getRealPath())
);
}
11. Queues
The Laravel queue service provides a unified API across a
variety of different queue back-ends.
$job = (new SendReminderEmail($user))->onQueue('emails');
$this->dispatch($job);
Available Queue Drivers:
Database, Beanstalkd, Amazon SQS, Redis, and synchronous
(for local use) driver
12. Task Scheduling
The Laravel command scheduler allows you to fluently and
expressively define your command schedule within Laravel
itself, and only a single Cron entry is needed on your
server.
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
DB::table('recent_users')->delete();
})->daily();
$schedule->command('emails:send')->weekly()->mondays()->at('13:00');
$schedule->command('emails:send')->withoutOverlapping();
}
15. Migrations
Migrations are like version control for your database.
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
});
16. Seeding
Laravel includes a simple method of seeding your database
with test data using seed classes.
<?php
use IlluminateDatabaseSeeder;
use IlluminateDatabaseEloquentModel;
class DatabaseSeeder extends Seeder
{
public function run()
{
DB::table('users')->insert([
'name' => str_random(10),
'email' => str_random(10).'@gmail.com',
'password' => bcrypt('secret'),
]);
}
}
18. Eloquent ORM - Soft Delete
● Active Record implementation
php artisan make:model User --migration
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
class Flight extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
}
24. Lucid * Feature
● As described in business, as a class name
● Runs Jobs - Steps in the process of accomplishment
CreateArticleFeature
LoginUserFeature
Controller Feature
Serves
30. Lucid * Job
A class that does one thing; responsible for the business logic
● Validate Article Input
● Generate Slug
● Upload Files To CDN
● Save Article
● Respond With Json
CreateArticleFeature
31. Lucid * Job
A class that does one thing; responsible for the business logic
● ValidateArticleInputJob
● GenerateSlugJob
● UploadFilesToCDNJob
● SaveArticleJob
● RespondWithJsonJob
CreateArticleFeature
32. Lucid * Job
A class that does one thing; responsible for the business logic
API architecture
We need to use micro frameworks for APIs
Laravel provides these features and it sets it apart from other PHP frameworks.
Same as filters in Yii
Can be defined
Globally
with route
group
Validate all requests coming from Twilio
Problems DI solves are “Inversion of Control” and “Dependency Inversion Principle”
Loosening dependencies by separate instantiation
Depend on abstractions rather than concretions
Dependency of UserRepository is injected automatically through Service Containers
Service container bindings are registered in Service Providers
We can replace these bindings with mock classes and testing can become simpler.
Laravel uses flysystem library to provide filesystem abstraction.
I guess Convention over Configuration is not specific to ORM
In Laravel it has more use in ORM as compared to Ruby On Rails in which most of the framework features work on this principle
Architecture: Outcome depends on how structures are connected. (DNA -> dinosaur)
Old/legacy projects like Shredd/MTSobek
New developer needs to understand where each piece of code resides
How Structures (Classes) like any service connected to other part of our code
High level or Top level view.
An expression of a Viewpoint.
Communicate Structures
Large application code
New developer
MVC example
Why use architecture
Utility and Helper Classes
Single Responsibility Principle