Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

2/23/2014

My toolset

Developers have some special relationships with the tools  they use for everyday work.  I am not exception.

From the beginning of my carrier, I really spent lot of time trying different editors, terminals, operating systems... I was very passionate about that . Sometimes I didn't do anything, but just tuning new terminal or editor, which I quickly replaced with new one. I was aware that it could lead me to insoncistency,  so I was trying to learn as much as I can about new tools. By learning , I was sticking my  nose everywhere - from the Linux kernel to the most highest abstractions.

I didn't mentioned that Windows very quickly become boring, there was nothing interesting there for me. So I become dedicated Linux/Ubuntu user.  And Linux is perfect platform for any kind of programming (well not for C# but you know what I mean ). No developer can convince me that his favourite OS is Microsoft Windows, if  he is not their employee.

I was very fascinated (and still I am) with different (mostly open source) project. It is incredible how such masterpieces like Apache or Vim are totaly free, and you have support for any kind of problems - and it is still free.

These days I am not changing my tools so often - due to fact that I found my (almost) perfect  setup and that I don't have so much time.

So here is a quick overview what I use in my daily practice:

Main OS:
Linux/Ubuntu
I know, I know real hackers are using Gentoo and Slack but Ubuntu, which is based on Debian unstable is really up to date with bleeding edge packages - which are necessery due to fast changing web environment. Ubuntu 14.04. is going to be LTS (long term supported) so after upgrading, I wont be moving further for years.

Main editor:
Vim
What to say about Vim ? If you havent tried it, then no words can express what can Vim mean to productivity. Vim is iconic software and represents more then just text based editor. If you can't find something in the form of Vim extension, then you didn't look carefully. From Vim (with the help of terminal) I can code, debug, test, git, fetch...

Terminal emulators:
I am doing most of my work moving between browser and terminal.
I was using Terminator for long. Terminator has one great feature - you can split windows vertically and horizontally quickly. It is fully supported with all kind of character-sets and just works. One thing that I missed in Terminator was lack of line spacing. Only one Linux terminal that has that feature is Urxvt. Line spacing for me was so important, so I decided to migrate to Urxvt. It more geeky terminal, that needs some advanced configuration, but when you tune it by your needs - there is no turning back. But, nothing is perfect. On Ubuntu you can't set Urxvt transparent background  because Compiz has some weird issues with it. If you help me solve this, I'll buy you a beer , no matter in which part of the world you are :) Along with Urxvt comes Tmux, terminal multiplexer for managing multiple sessions.

Browsers:
Since I am primary a web developer, browser for me are just clients, with additional features. Chrome/Chromium team has produced awesome software. Chrome/Chromium developer tools is very powerful and if used correctly it can increase productivity, not just on client side. Chromium/Chrome is very opened toward developers and by just entering chrome://chrome-urls in the address bar, you can enjoy all different setting and statistics...

And that is it. There is so much power in everything above, that trying something else at this point would be just a waste of time.

At the end, I have to mention IDE-s. Only one that I was using for some time was KomodoEdit. It has good Linux support and some more good things  but that was all. I just don't know how to work in such environment. My fingers are in love with Vim keyboard bindings :)

Thanks for reading.

2/22/2014

Symfony in Laravel

Last couple of days i spent reading this tutorial. It is Fabien Potencier (creator of Symfony) online guide on how to create your own PHP framework on top of Symfony components. 

The reason I was reading this is because Laravel is heavily dependent on Symfony. I was trying to find out why Taylor Otwell (Laravel creator) choose Symfony to rely on.

I also watched some Fabien Potenciers video presentations and read some of his articles. I have to say, that this guy is not ordinary PHP geek, who is just a creator of one successful framework. There are some really great ideas in his talks and I highly recommend you to read something like this article. I was impressed wich some ideas like MVC is not a part of web, and Symfony doesn't have domain logic layer. If you thinks about this, there is a lot of truth inside. I found myself beeing amazed how much I learned from Symfony. 

So lets see what and why is Laravel using. The most important part of Symfony in Laravel is a HTTPKernelInterface. As a developer you know that PHP is interacting with server through SAPI (server application  programming interface). SAPI in PHP is basically implemented in the form of header and echo method. Through SAPI, PHP is sending its response to server. On Apache, default SAPI for PHP currently is Apache2handler. There is one more interface, for interacting with server - CLI SAPI or command-line interface. This is how PHP interact with server through command line. HTTPKernelInterface is build on top of idea that PHP needs better way to interact with server and clients. HTTPKernelInterface has just one method - handle. And that is all. Good programming practice suggest that interfaces should follow interface segregation principle. That principle states that no client should depend on the method that it doesn't use. So, that why there is only one method inside, that should provide all response logic.

Laravel is implementing this interface in the main Application class.There is a lot of things happening inside this implementation - from route collection lookup, to custom response. When you run app->run method, you are triggering stack that will end with returning response to client. Application has some bootstrap process before method run is triggered, but this method is the heart of Laravel HTTP handling logic.

It should be no surprise that both - Laravel request and response  are extensions of Symfony HTTPFoundation classes. So, Laravel is built on top of Symfony - I guess Taylor Otwell was first reading that tutorial :)

Web appllications are complex to develop, due to HTTP stateless nature.
On one end, we as developers have to take care about transport mechanism (protocol), and on another end we have to deal with domain logic (MVC). On native deskop applications, there is no HTTP. Everything is managed locally, and you can develop application in one consistent environment. I think that is the main reason for popularity of Single Page Web Applications. They are trying to simulate desktop environment, with moving most of logic to client. We will see how that trend is going to evolve.

Symfony ecosystem is huge. It is established PHP framework, so Laravel is gaining much of its strength from Symfony. So, if you want to learn more about Laravel, take some time and git clone Symfony. Besides weird yaml format (Laravel is using json) and some Symfony specific configurations, you can learn something new about architecture and design.

Thanks for reading. 



2/12/2014

SOA - Service Oriented Architecture in Laravel

My previous post title was n-tier meets MVC.
In this post I want to add one more thing to that conclusion - n-tier meets MVC with the help of SOA.

Yes, besides n-tier (client/server) and MVC our favourite framework is implementing one more well known architectural pattern. It is called SOA or Service Oriented Architecture. Wikipedia has got pretty good explanation of SOA.


Take a look at this sentence from Wiki:
Service provider: The service provider creates a web service and possibly publishes its interface and access information to the service registry.

Sounds familiar ? Well it took me a while untill I finally realized what is Laravel doing in one of its core parts. Like many Laravel developers I was struggling with facades, providers and containers terminology without knowing that it is just an implementation of well known pattern. Modified, but concept is still the same.

Less obvious part of this  is why Taylor Otwell actually decided to design framework with SOA style incorporeted ?
Knowing that he has strong .NET background can help. In Microsoft world, they traditionally care about services. I was teached to think Restfully, so this was hard concept to grasp.

So the story is:

In the middle of the Laravel  kingdom lives Application, that depends on its citizens and servants. Application can exists by its own, but there is no point in empty kingdom. Every kingom has a treasury.  So they build one. In this kingdom it is called Container . 
Then Application defined  a rules and exposed them publically through its main  accociate - ServiceProvider class. All new citizens have to behave and look the way it is defined by the king.
ServiceProvider announced that everyone who wants to be a part of Application kingdom must implements two methods:

  • register and
  • boot

Register to become part of kingdom and boot to invite their friends to join. Also, Application allows some level of freedom to their citizens and let them choose their names and how they will be called. Speeking in Laravel terms, they can use Aliases and Facades for their access.

But, not everything is perfect . Some citizens are on the higher position then others. So they are treated specially. e.g. Request class is called very early, and it is bound directly, without use of ServiceProvider class.
On the other hand some citizens choose fancy names like Config, but underneath they are originally called Repository.

What would be a kingdom without a police ? Events are everywhere.
They provide welcome to every new citizen (provider) and take care of illegal activities. If something bad happened they will fire its main weapon - Exception. In our kingdom it is allowed to have private police.
It is no problem. Even better - it is a free gift from one of the highly rated Applications servants. If you want to take care if right type of rules are applied in your Validation, just call Event police - and it will fire all exceptions.  

So, even it sometimes looks that things are out of order in typical Laravel application, it is just because developer didn't understood properly how framework is internally designed and with what intention in mind. In all other casess, we have great tool for building web applications.

Thanks for reading.

2/09/2014

n-tier meets MVC in Laravel


This is the post about two fundamental architectural patterns that can be found in most todays web framerworks. These patterns are:

  • n-tier represented as client/server model and
  • MVC (model,view,controller)

There is a lot resources online client/server, n-tier so I will take a look at Laravel specific implementations of these patterns. You can argue is MVC architectural or design pattern. I think MVC is closer to well established arch patterns due to its usage and overall complexity.

In Laravel we can exactly detect boundary between them as so as their main flow. Client model starts in the form of HTTP request, which is received from the browser (mostly) and provided to main Application class:

public function __construct(Request $request = null)
 {

  $this->registerBaseBindings($request ?: $this->createNewRequest());

  $this->registerBaseServiceProviders();

  $this->registerBaseMiddlewares();
 }


Request comes in a form of Laravel request which extends Symfony class. After application receives a request, it will registered it as a protected property (object). In this phase, flow is pretty straightforward. If there is no custom middleware functionality, request will end waiting for handler method. There are some minor processing like attaching session driver, but main job is done in a layer that comes after.

I mentioned middleware, which is actually all functionality that lives in a space between the reqeust hits the internal application routes. Laravel (from 4.1 Iversion) implements StackBuilder middleware, which can be used  like a flyweight alternative to caching and session management (and for some other things).

Here is a method that implements StackBuilder:

protected function getStackedClient()
 {
  $sessionReject = $this->bound('session.reject') ? $this['session.reject'] : null;

  $client = with(new \Stack\Builder)
      ->push('Illuminate\Cookie\Guard', $this['encrypter'])
      ->push('Illuminate\Cookie\Queue', $this['cookie'])
      ->push('Illuminate\Session\Middleware', $this['session'], $sessionReject);

  $this->mergeCustomMiddlewares($client);

  return $client->resolve($this);
 }


StackBuilder andLaravel Application class implements Symfony\HttpKernelInterface in the form of handle method. That is why it is called stack - it just forwards request further down the stack till it reaches main Application handler

When request hits Application handler, it is on the door of MVC part of Laravel, which leads further to domain logic and the heart of application.

Take a look at the main handler:

public function handle(SymfonyRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
 {
  try
  {
   $this->refreshRequest($request = Request::createFromBase($request));

   $this->boot();

   return $this->dispatch($request);
  }
  catch (\Exception $e)
  {
   if ($this->runningUnitTests()) throw $e;

   return $this['exception']->handleException($e);
  }
 }


As can be seen, it is dispatched to router, for further processing and which will result with HTTP response.   For now I wont go deeper into source code, since point of this post was just to show conceptual boundary between these two layers. This boundary is sometimes not so visible, due to frameworks specific implementations. One thing that is worth mentioning is that client/server model is dominant model in distributed systems like internet (where client is present), while MVC originated in the deskop environment. If not designed properly, applications made with the mix of these patterns can become very complex and lead to bugs and potential break. For me, it was very important to reckognize them in Laravel, so I could have better insight into awesome framework design.

Thanks for reading.

2/03/2014

Laravel sandwich

This morning, while reading  my favourite PHP frameworks code, it occured to me that Laravel application looks like one big, yummy sandwich. Well, that may sound weird but sometimes while coding, language concepts are presented in my mind like something that have nothing to do with programming. Or it does ?

So Laravel sandwich like every other is consists of three main parts:
  • top piece of bread (Application is called)
  • yummy layer (all good things like config, routes,controllers,models...)
  • bottom piece of bread (return what the client was asking)

When we transform these food terms into programming we got this:

//top piece
        $app = new Illuminate\Foundation\Application;

       // what was called
 public function __construct(Request $request = null)
 {
    
  $this->registerBaseBindings($request ?: $this->createNewRequest());
   
  $this->registerBaseServiceProviders();

  $this->registerBaseMiddlewares();
 }

As you can see above, app is called with provided request - which is little later registered into container. I was wondering why request is not registered as service provider - now I now . Request has to come first, before any bindings.
And that's all, belive it or not. Nothing fancy is happening here. Just some administrative tasks in the form of registering request into application. Yes, behind scene Symfony is doing a lot work while receving and preparing HTTP request, but it is not important for now.

Yummy part lives in the middle of our sandwich, and presents most delicious layer of Laravel delicacy. In fact we can say that this layer is most important in whole Laravel application. Here we can find all calls to routes, controllers, models, db - in other words it is the heart of domain layer, mean machine that has to be controlled somehow and from somewhere. If you don't understand what do I mean when I talk about "yummy layer" take a look at the content of these folders and files:
app/
        commands/
        config/
        controllers/
        database/
        lang/
        models/
        start/
        storage/
        tests/
        views/
        filters.php
        routes.php
You will be looking in the heart of nuclear reactor. That power needs some kind of control, or it will blow away everything. So let's push the red button. Or, let's eat our sandwich. We can do that with this method:

App::run();

        //in other words

 public function run(SymfonyRequest $request = null)
 {
  $request = $request ?: $this['request'];

        // calls dispatch route method
  $response = with($stack = $this->getStackedClient())->handle($request);

  $response->send();

  $stack->terminate($request, $response);
 }

Not so obvious ah ? Well I hope I will visit Laracon one day and thanks Taylor Otwell for this awesome piece of software that we enjoy somuch. Till next post, try to dig deeper into Laravel source code from App:run() point - there is a lot things inside.

I hope you like my post, and sorry for beeing too abstract sometimes.

2/01/2014

Laravel environments setup

Why does it matters ?

Ability to have multiple environments and to switch between them quickly is of big importance for any non-trivial web development task.
For example, if you test your application data layer, test code shouldn't be hitting real database tables in any case. Instead it should rely on mocked and prototyped tables that is easy to create and drop.
Laravel makes that process very easy by offering three main types of environments:

  1. development
  2. production
  3. testing
How to choose environment ?

Entry point for choosing is located in bootstrap/start.php file in the root folder of Laravel project, at ine 29 (Laravel version 4.1):

Original function looks like this:

$env = $app->detectEnvironment(array(
 'local' => array('your-machine-name'),
));


As can be seen, env is detected by providing array with env name and value in the form of key-value pair.

My custom version looks like this:
$env = $app->detectEnvironment(function()
{
    return getenv("ENV") ? : "local";
});


Instead of array, this function accepts function(closure) that returns type of env. That type will be auto deteced with the use of ternary operator.

How to setup environment ?

By just choosing, we didn't do much. We have to customize desired env and tell Laravel when to find them. All env settings are stored under app/config directory.  Default env is production, so if you don't create new, Laravel will treat all config settings as production. Easy task of setting custom env is done by just creating new folder under app/config directory. So if you want to have one env for development and one for production, just create new folder and name it development. Now all that we place inside will be red by Laravel only in case we explicitly choose in bootstrap/start.php file.  Note that development is just a convention, I instead name my development env as local - It is easier that way for me to differentiate. Name is not important, as long as it is in sync with name of the folder and vice verse. Most common reason to have different env are a database settings. By default, they are stored in app/config/database.php file. 

Here is my  database.php file, placed under app/local/ directory:
array(
  'mysql' => array(
   'driver'    => 'mysql',
   'host'      => 'localhost',
   'database'  => 'local-db',
   'username'  => 'root',
   'password'  => '123456',
   'charset'   => 'utf8',
   'collation' => 'utf8_unicode_ci',
   'prefix'    => ''
        )
)];


These setting works under local environment  common ( apache, localhost, mysql configuration ).

 And here are production settings: 
array(
  'mysql' => array(
   'driver'    => 'mysql',
   'host' => getenv("DB_HOST"),
   'database' => getenv("DB_NAME"),
   'username' => getenv("DB_USER"), 
   'password' => getenv("DB_PASSWORD"),
   'charset'   => 'utf8',
   'collation' => 'utf8_unicode_ci',
   'prefix'    => ''
      )
)];


Note that in order for these production values to have affect, you'l have to "catch" env variables that are specific to server environment.
Here I simply import them with native PHP getenv function.

Last and not so commonly used is testing environment. It is provides automatically by Laravel, so you don't have to worry about that. 

Here is how Laravel detects if we are using testing env:

public function createApplication()
 {
  $unitTesting = true;

  $testEnvironment = 'testing';

  return require __DIR__.'/../../bootstrap/start.php';
 }

This is excerpt from TestCase class which extends PHPUnit_Framework_TestCase and is locate under app/tests directory.
Again, in order this to work, we have to create new testing directory and place all out settings inside. One gotcha when migrating database table for testing purposes is to forgot to tell Laravel the type of env we want that table to be used for. If don't, Laravel will be using default environmet. 
To choose right type of env it is enough to add --env="testing" at the end of migration command like this:

php artisan migrate --env="testing"

It can be used for local/development purposes also.
php artisan migrate --env="local"

Thanks for reading.