News

10 ways to make PHP beautiful

Discover how to add elegance to your code with the help of the popular Laravel framework

laravel

1. Eloquent Queries

Laravel offers one of the most powerful Active-Record implementations in the PHP world. Say you have an ‘orders’ table, along with an ‘Order’ Eloquent model:

001 class Order extends Eloquent {}

We can easily perform any number of database queries, using simple, elegant PHP. No need to throw messy SQL around the room. Let’s grab all orders.

002 $orders = Order::all();

Done. Or maybe, those orders should be returned in order, according to the release date. That’s easy:

003 $orders = Order::orderBy(‘release_date’,     ‘desc’)->get();

What if, rather than fetching a record, we instead need to save a new order to the database. Sure, we can do that. With Laravel, tasks that used to be cumbersome to perform are laughably simple.

001 $order = new Order;
 002 $order->title = ‘Xbox One’;
 003 $order->save();

2. Flexible Routing

Laravel is unique in that it can be used in a number of ways. Prefer a simpler, more Sinatra-like routing system? Sure, Laravel can offer that quite easily using closures.

001 Route::get(‘orders’, function()
 002 {
 003    return View::make(‘orders.index’)
 004        ->with(‘orders’, Order::all());
 005 });

This can prove helpful for small projects and APIs, but, chances are high that you’ll require controllers for most of your projects. That’s okay; Laravel can do that, too!

001 Route::get(‘orders’, ‘OrdersController@    index’);

Done. Notice how Laravel grows with your needs? This level of accommodation is what makes the framework as popular as it is today.

3. Easy Relationships

What do we do in the instances when we must define relationships? For example, a task will surely belong to a user. How might we represent that in Laravel? Well, assuming that the necessary database tables are set up, we only need to tweak the related Eloquent models.

001 class Task extends Eloquent {
 002    public function user()
 003    {
 004        return $this->belongsTo(‘User’);
 005    }
 006 }
 007 class User extends Eloquent {
 008    public function tasks()
 009    {
 010        return $this->hasMany(‘Task’);
 011    }
 012 }

And, with that, we’re done! Let’s grab all tasks for the user with an id of 1. We can do that in two lines of code.

001 $user = User::find(1);
 002 $tasks = $user->tasks;

However, because we’ve defined the relationship from both ends, if we instead want to fetch the user associated with a task, we can do that too.

001 $task = Task::find(1);
 002 $user = $task->user;

4. Form Model Binding

Often, it can be helpful to link a form to a model. The obvious example of this is when you wish to edit some record in your database. With form model binding, we can instantly populate the form fields with the values from the associated table row. Because the form in the code below is now linked to a specific ‘Order’ instance, the inputs will display the correct values from the table.

001 {{ Form::model($order) }}
 002    <div>
 003        {{ Form::label(‘title’, ‘Title:’) }}
 004        {{ Form::text(‘title’) }}
 005    </div>
 006
 007    <div>
 008        {{ Form::label(‘description’,         ‘Description:’) }}
 009        {{ Form::textarea(‘description’) }}
 010    </div>
 011 {{ Form::close() }}    012

5. Cache Database Queries

If you have too many database queries, your application can very quickly become like molasses. Luckily, Laravel offers a simple mechanism for caching these queries, using nothing more than a single method call.

Let’s grab all ‘questions’ from the database, but cache the query, since it’s not particularly likely that this table will be updated all that frequently.

001 $questions = Question::remember(60)->get();

That’s it! Now, for the next hour of incoming page requests, that query will remain cached, and the database will not even be touched.

6. View Composers

You’ll encounter situations when multiple views require a certain variable or piece of data. A good example of this is a navigation bar that displays a list of tags.

To keep controllers as minimal as possible, Laravel offers view composers to manage things like this. With this piece of code, any time that the ‘layouts/nav.blade.php’ view is loaded, it will have access to a variable, ‘$tags’, equal to the provided array.

001 View::composer(‘layouts.nav’,         function($view)
 002 {
 003    $view->with(‘tags’, [‘tag1’, ‘tag2’]);
 004 });
 005

7. Simple Authentication

Laravel takes a very simple approach to authentication. Simply pass an array of credentials, likely fetched from a login form, to `Auth::attempt()`. If the provided values match what is stored in the `users` table, the user will instantly be logged in.

001 $user = [
 002    ‘email’ => ‘jeffrey@laracasts.com’,
 003    ‘password’ => ‘password’
 004 ];
 005
 006 if (Auth::attempt($user))
 007 {
 008    // user is now logged in!
 009    // Access user object with Auth::user()
 010 }

What if we find that we need to log the user out – perhaps, when a ‘/logout’ URI is hit? This is easy too, as is demonstrated in the following code:

001 Route::get(‘logout’, function()
 002 {
 003    Auth::logout();
 004
 005    return Redirect::home();
 006 });

8. Resources

Working RESTfully in Laravel has never been easier. To register a resourceful controller, simply call ‘Route::resource()’, as shown on the following page. 001 Route::resource(‘orders’,         ‘OrdersController’);

With this code, Laravel will register eight routes:

- GET /orders
 - GET /orders/:order
 - GET /orders/create
 - GET /orders/:order/edit
 - POST /orders
 - PUT /orders/:order
 - PATCH /orders/:order
 - DELETE /orders/:order

Further, the companion controller may also be generated from the command line:

001 php artisan controller:make         OrdersController

Within this generated controller, each method will correspond to one of the routes above. For example, ‘/orders’ will map to the ‘index’ method, ‘/orders/create’ will map to ‘create’, etc. We now have the necessary power to build RESTful applications and APIs with ease.

9. Blade Templating

While, yes, PHP is by nature a templating language, it hasn’t evolved to become an overly good one. That’s okay, though; Laravel offers its Blade engine to fill the gap. Simply name your views with a ‘.blade.php’ extension, and they will automatically be parsed, accordingly. Now, we can do such things as this:

001 @if ($orders->count())
 002    <ul>
 003        @foreach($orders as $order)
 004            <li>{{ $order->title }}</li>
 005        @endforeach
 006    </ul>
 007 @endif
 008 

10. Testing Facilities

Because Laravel makes use of Composer, we instantly have PHPUnit support in the framework out of the box. Install the framework and run ‘phpunit’ from the command line to test it out. Even better, though, Laravel offers a number of test helpers for the most common types of functional tests. Here we’re going to verify that the homepage returns a status code of 200.

001 public function test_home_page()
 002 {
 003    $this->call(‘GET’, ‘/’);
 004    $this->assertResponseOk();
 005 }

Or maybe we want to confirm that, when a contact form is posted, the user is redirected back to the homepage with a flash message.

001 public function test_contact_page_    redirects_    user_to_home_page()
 002 {
 003    $postData = [
 004        ‘name’ => ‘Joe Example’,
 005        ‘email’ => ‘joe@example.com’,
 006        ‘message’ => ‘I love your website’
 007    ];
 008    $this->call(‘POST’, ‘/contact’, $postData);
 009    $this->assertRedirectedToRoute(‘home’,     null, [‘flash_message’]);
 010 }
×