Playing With Laravel 4 (the PHP MVC framework) And Telerik UI

It’s been a rough week, honestly. I’ve had to rebuild my development environment on my Mac twice because of compatibility issues with Homebrew an XCode versions, I blew up my PHP install twice, set up Vagrant with a VM to do things but it had the wrong version of PHP, and then couldn’t use MacVim because of a plugin that had to be rebuilt with the updated Homebrew and XCode versions. But I’m here. I’ve got Laravel 4 installed on my Mac, and it’s working finally! And I have to say, I really like what I see so far.

If you haven’t used or heard of Laravel before, think of it like Rails, Django or ASP.NET MVC, except for PHP. It’s a pretty classic looking MVC setup for web development, as far as I can tell. Maybe someone with more experience can say otherwise, but I found it to be a very comfortable place to write code from this perspective. 

Why Laravel? Why Now?

I’m a sucker for learning, honestly. I love trying out new toys, banging them against walls and hitting them with hammers to see where they break, and wondering if I can put them back together. Laravel isn’t exactly new, of course, but it’s new to me. I’ve known about it for a while now, and have done a little bit of work with some raw PHP in the last year (raw == no framework other than what’s built in). So as I’m heading out the door of Telerik and Kendo UI this week, I thought I would try my hand at this lovely framework, see what it’s all about, and see what happens when I try to combine the Telerik UI (FKA / AKA “Kendo UI”) PHP extensions to Laravel. 

A Complete MVC Framework

My over-all impression of Laravel is that it is a well done, complete implementation of an MVC framework for a web server, in the vein of Ruby on Rails. It has that familiar structure of models, views and controllers for folders and objects. 

NewImage

You also have a router to configure, migrations to build, and lot of other common configuration and expected things inside of a modern MVC framework. It even looks like there is some sort of asset pipeline type of functionality. The hello.blade.php file, for example, gets parsed by the Blade view engine. I’m not sure how far this functionality extends – I haven’t tried adding multiple steps via multiple . file extensions yet. But, I know that if you rename this file to just “hello.php” it won’t be parsed as a blade file. It will just be a standard PHP file.

Controllers Done Right

One of the things I really like about Laravel is how it handles actions in controllers. In Express for NodeJS and Ruby on Rails, as counter-examples, an action in a controller is directly responsible for executing the action of the controller. If you want to render a view, you render the view in the controller’s action. If you want to redirect, you redirect right there in the action. This has a tendency to push people toward having a lot of code in their controllers, in my experience. Laravel does it right, in my opinion. It doesn’t want me to execute the action right there in the controller method. Instead, it wants me to build an action object that I return from the controller method. 

<?php

class HomeController extends BaseController {

  public function showWelcome()
  {
    $users = User::all();
    return View::make('hello')->with('users', $users); 
  }

}

I know this doesn’t look very different off-hand, but under the hood it is different. I’m not executing the view rendering and manipulation in the controller method. This is evidenced by the call to ->with(...) on the end of the view creation. If this line were executing the view rendering, I wouldn’t be able to call the with method at this point. I would have to pass the view parameters in as an argument to the View::make call (which is one way of doing this, for what it’s worth). 

If you look at the code for the View object, you’ll see that the with method doesn’t perform any actions when it’s called. It stores information for later use, based on the parameters that are called. Later, when the View object’s render method is called, it calls out to the actual rendering services to get the job of rendering done. Since you never have to manually call render in your controller method, it can be deduced that the View object is a sort of command object that is being configured in the controller and then executed at a later point in time. 

This little difference – not actually executing the action during the controller method – can mean the difference between writing a ton of ugly code in a controller and extracting specific actions in to re-usable objects for your application. You’ll be able to consolidate similar controller method in to objects that you can use in multiple controllers, reducing code and maintenance in your controllers. This is definitely a good thing.

Connecting PHP Extensions For Kendo UI

After playing with Laravel for a bit, I decided to grab the Kendo UI PHP extensions and see how much effort it would take to load this in. The download for these extensions comes directly from the Telerik.com site, and isn’t available as a Composer package at the moment (at least, not that I could see).

I started by copying the Kendo UI PHP files in to a “lib” folder:

NewImage

I also set up the standard Kendo UI JavaScript and CSS files in the /public folder of the project, and added those references to my project layout.

NewImage

You need the Kendo UI JavaScript and CSS to run any of this, because the PHP extensions don’t build the HTML output directly. They produce JavaScript that is used in your browser to configure and run your Kendo UI controls. You can learn a bit more about that in my PHP demo videos for Kendo UI.

After getting the files in place, I updated my composer.json file to include the “lib” folder in the autoload paths.

"classmap": [
  "app/commands",
  "app/controllers",
  "app/models",
  "lib",
  "app/database/migrations",
  "app/database/seeds",
  "app/tests/TestCase.php"
]

I was trying to get the lib/Kendo/Autoload.php file to load automatically, as the name suggests, but I’m probably configuring the composer.json file incorrectly. What I ended up doing is adding a require_once to my /bootstrap/autoload.php file.

require_once 'lib/Kendo/Autoload.php'; 

This works, so it’s good enough for me. Someone else will hopefully see this and correct me on how to make composer.json load things automatically. :)

**UPDATE**

Thanks to Andrew MacKenzie, in the comments below, I now know that I can run composer dump-autoload after changing my classmap settings. This rebuilds the classmap and prevents me from having to add the require_once line in my autoload.php scripts. Thanks, Andrew! :)

Using Kendo UI Controls

Having set all that up, getting a Kendo UI control in place was easy. To start with, I dropped in a DatePicker, because it is simple to create and doesn’t need a data source to show things. I was originally going to put this in my view directly, but decided that I wanted my $datePicker variable in the controller, and would just pass that to my view with the other args and data. This way I can configure the $datePicker with anything I need, and keep all that configuration and logic out of the view.

public function showWelcome()
{
  $datePicker = new \Kendo\UI\DatePicker('datepicker');
  $users = User::all();

  $args = array(
    'users' => $users,
    'datePicker' => $datePicker
  );

  return View::make('hello')->with($args);
}


@extends("layout")

@section("style")
  <link href="/kendoui/styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
  <link href="/kendoui/styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
@stop

@section("javascript")
  <script src="/kendoui/js/jquery.min.js"></script>
  <script src="/kendoui/js/kendo.web.min.js"></script>
@stop

@section("content")
  <div class="welcome">
    My first laravel app
    <ul>

    {{ $datePicker->render() }}

    @foreach($users as $user)
      <li>{{ $user->name }}</li>
    @endforeach
    </ul>
  </div>
@stop

With that in place, reloading my view shows the DatePicker control as expected:

NewImage

Now to get some data in place.

I started with the Laravel quickstart guide of adding a User table and model, and I added some junk data to my user table. This lets me load up data using the User model and assign it to the datasource of a Kendo UI control. 

public function showWelcome()
{
  $datePicker = new \Kendo\UI\DatePicker('datepicker');
  $users = User::all();

  $ds = new \Kendo\Data\DataSource();
  $ds->data($users->toArray());

  $dropList = new \Kendo\UI\DropDownList('droplist');
  $dropList
    ->dataTextField("name")
    ->dataValueField("id")
    ->dataSource($ds);

  $args = array(
    'users' => $users,
    'datePicker' => $datePicker,
    'dropList' => $dropList
  );

  return View::make('hello')->with($args);
}


@section("content")
  <div class="welcome">
    My first laravel app
    <p>
      {{ $datePicker->render() }}
    </p>
    <p>
      {{ $dropList->render() }}
    </p>
  </div>
@stop

The awesome thing to note here, is the use of $users->toArray(). The Kendo UI PHP wrappers are smart enough to take this array of objects and convert it in to a JSON document for you, in your HTML. When the page gets rendered, then, the browser has all the data it needs for the drop down list. The result is what you would expect, then. A nice drop down list with the data loaded from the Users::allI() call.

NewImage

Of course this doesn’t cover loading data at runtime, using AJAX. But i’ll let my videos on the PHP extensions cover that for you.

Fun Stuff, Lots more

In spite of my initial anger and frustration of not being able to get Laravel installed and working, I’m really enjoying this framework. My problems turned out to be my Homebrew install, anyways, so it really isn’t fair to say that Laravel was difficult to install. Honestly, it wasn’t – once I got homebrew fixed, Laravel installed pretty quickly and only took a few rounds of looking through the quick start guide and installation docs to get me up and running. 

If you’re considering a jaunt in to some PHP work, and need a good place to go for writing well structured, MVC style server code, check out Laravel. And if you want to add a modern UI framework to the front end of it, check out Telerik UI (“Kendo UI”) – you have the option of writing the JavaScript  yourself, or using the PHP extensions that I’ve shown here so that you don’t have to write any serious amount of JavaScript.

This is shaping up to be a great combination of tools – enough that I would almost feel comfortable taking on a project with Laravel and Telerik UI at this point. But there’s a lot more for me to learn about Laravel and how it really works before I do that. :)


Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs SignalLeaf.com - the amazingly awesome podcast audio hosting service that everyone should be using, and WatchMeCode.net where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in Kendo, Laravel, Model-View-Controller, PHP, Telerik. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • khalidabuhakmeh

    Funny, I saw your tweet earlier on Twitter and I thought to myself: “Hmm… that looks like Laravel code.” Then I packed up my bags and ran for the hills because I knew PHP was coming.

    I’m amazed at how close these MVC frameworks are getting when you boil it down to the core. If I squint it, I might mistake if for ASP.NET MVC.

    Pretty cool post. :)

    • http://mutedsolutions.com Derick Bailey

      lol, yeah, it reminds me so much of ASP.NET MVC, Rails, and every other MV* web server framework I’ve used. It’s nice to have that comfortable feeling, even when dipping in to a different language / runtime!

      • http://getcloudigniter.com/ Zack Kitzmiller

        Taylor was a ASP.NET dev in a previous life. It’s heavily inspired by it.

        • http://mutedsolutions.com Derick Bailey

          oh, nice! i didn’t know that. it certainly shows, though, with the way actions are handled in controllers. that really is the right way to do actions. so powerful and flexible.

  • Andrew MacKenzie

    on the autoload issue, after you added `/lib` to the classmap array, did you run a `composer dump-autoload` to rebuild the classmap?

    • http://mutedsolutions.com Derick Bailey

      BOOM! that got it! Thank you for that. :D

  • Ryan

    To get the Kendo autoload file run, add `lib/Kendo/Autoload.php` to autoload.files in the composer.json file. Classmap will only autoload a file when you call for the class within that file https://getcomposer.org/doc/04-schema.md#classmap

  • Rinck

    Thanks for the nice write-up! I too use both Kendo UI + PHP Wrappers and Laravel 4 and find it nice to see others using this powerful combination! I recently wrote a small tutorial on the Kendo forums about setting up a private composer repository so you can load your Kendo files using composer! I use it for all my projects now and it makes updating and installing kendo even easier! You can check it out here: http://www.telerik.com/forums/loading-kendo-ui-through-composer

    Hope that helps someone! :)