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

12/16/2013

Dissecting Laravel Application class



This class along with core framework represents cornerstone of internal Laravel machinery. In the spirit of good software design it is responsible for one thing. This class, speaking from the highest level is conducting everything that exist in the framework core. It provides life to all service providers. But, underneath the simple surface we can find very sophisticated design with complex relationship to and from client and framework. Let’s take a peak inside.

This class is instantiated very early in application life cycle. It happens in start.php file under bootstrap/ folder . And it is initiated by client request. We already can see that it has direct relationship with HTTP protocol and transport layer. To proof take a look at Applicaton constructor - it is expecting Request object as it’s argument:

//
public function __construct(Request $request = null)
{
$this->registerBaseBindings ($request Request::createFromGlobals(

$this->registerBaseServiceProviders();

$this->registerBaseMiddlewares();
}
//

In case there is no explicit Request, constructor will fetch request data from globals. It is internally done by Symfony request class - which is used by Application. Alongside Symfony request class , our Application has relationships with 17 classes. We can see that Application is simply using those classes which are represented as service providers. They create a compositional relationship. On the other hand, our Application is extending Container class (in other words becomes a container ) and implements three interfaces. So already it can become a mass if the Laravel developers didn’t provide a way to organize those relations . It is done through Facade design pattern and Container bindings and resolving of service providers. These patterns deserves a dedicated posts, so let’s get back to more abstract view. One great geeky detail is that Application instance is registered to itself as a service provider in foundation/start.php file.

Application class contains 48 public and 13 protected methods. Those methods can be seen as implementation of Application responsibility to conduct all service providers in a consistent way. Most of ( but not all) Application responsibility is concetrated around service providers and HTTP request. It is not surprising since considering how important are those areas.

At the end of this brief overview try to imagine how would it be to create “headless” Laravel application or application without application ? Download core framework from the github and take a look at tests directory. Creator of Laravel did just that, by testing and simulating real environment - without app layer. Application class is present, but not outside of framework. It is instantiated from the tests. In my opinion developing in this way ( with tests ) is what is separating a real web-programmer from the rest of the world :)

Thanks for reading.

12/15/2013

Laravel architecture layers

Let's talk about Laravel structure. What is it and why having good structure is important - in terms of built in framework architecture.

In this post, I will categorize some Laravel layers as architectural. It may sometimes clash with classic definition of architecture, but it helps me to build good mental model in order to understand framework.

From the highest level, around and inside of Laravel we can reckognize:
  1. Client-server architecture
  2. Laravel specific micro-architecture ( my term )
  3. MVC (model, view, controller)

Client-server architecture lives on a level that is not specific to Laravel, but is implied by the framework. You can implement client-server architecture without Laravel, but opposite is not possible. Web as distributed system uses HTTP protocol as a transport layer to provide content to clients in the client-server model. It is true without any server side processing. Web 1.0 or static web is perfect example. Client-server model as such ( with transport protocol ) underlines whole Laravel implementations. It is implied that we will be writing applications that uses it. Further, we can say that client-server model with HTTP is a kind of edge layer to framework, which simply passes data to framework and give back response in the form of HTML document ( mostly ). Everything else is happening inside  framework - in  another Laravel specific layer. Point of entry to Laravel from client request is a public folder, which is read by server. After Laravel reckognize that request, it will forward data along with path and headers to something that I call Laravel micro-layer. HTTP request is indeed very simple, and there is nothing complicated with it. Best way to think about client-server model is as a transport mechanism that delivers data to some address.

Laravel specific micro-architecture is a middle layer that ties all pieces of framework together and connects client with Laravel. It is represented inside app folder structure. For me, best way to think about this layer is as  internal command-line for Laravel implementation. If you think, it acts like a CLI by calling core API and organizing service providers into meaningful structure. It is possible to interact with core without app layer, but that is not very useful if you are not writing tests. So app layer is a front-end layer of two part internal Laravel architecture. It becomes obvious whan you download core framework from github, without application. Developers spend most of their time in app layer, since it is made for interactiong with Laravel internals. App layer is at the deeper level represented in the form of Application class - a class that server as a glue for all service providers.
Think about service providers as a row power for your application, that comes in many forms. That power should be used in a way that is appropriate for you app. Service providers have their own responsibilities and are already ready to use. Thinking about providers leads us to next layer.

MVC (model, view, controller) is a well known architectural pattern for separating view from data (model). It is implemented in a Laravel through Model, View and Controler folders in application along with their associated classes. As you can guess, MVC classes are provided to application like a service-providers. MVC providers should be considered as primary points of organization and interaction inside application. Everything else is related to MVC. That's why there are dedicated MVC folders in application. If client-server model is responsible for physical separation ( or n-tiered ) MVC represent logical division inside application. Client-server model is exposed to clients while MVC is exposed to developers. All other providers are directly of indirectly related to MVC. For example session, cookies, filesystem, cache, database - these are all persistance mechanisms that finds their place in MVC designed Laravel application. In fact MVC is dominant pattern in the web frameworks, so it is not strange that Laravel is implementating it in its own way.

Everything else beneath MVC and overall architecture belongs to design decisions - how to connect or interact with providers, or how to extend their functionallity. Architecture establishes common structure in which design is possible. With Laravel this is represented through layers described above. I think that it is crucial for serious Laravel developer to become familiar with this layers, in order to master this awesome framework.

Thanks for reading.


12/14/2013

How I moved to PHP thanks to Laravel

Structure is one of the area that brought me a lot of pain while learning programming.

 If I tell you that my first language was Javascript, you'll understand why that's the case. I don't have anything against JS, I love and use that language daily. It had awesome brain-teasing mix of paradigms. Problem is ( as noticed by many developers ) that JS is lacking a good structure. It can especially confuse someone who is introduced to programming with Javascript as a first language ( like me ). With JS you are launhed straight into orbit of closures, prototypes, mutability and incredible dynamism.

That's why, in one moment of my career  I decided to move to some more traditional and better structured language. PHP was somehow natural choice, since I am a web developer. In the beginning ( while PHP was mostly procedural and represented by Wordpress and family ) I couldn't quite grasp it. I was a experienced JS commando that used to shoot with first class functions and throw objects around freely. So PHP wasn't a good choice at that time. And then came newer version of PHP that introduced support for object-oriented and functional  paradigm (a among other goodies ).

Along with the PHP transformation Laravel was born, and I was hooked. I had finally language and framework in which I can approach web development in the way I want ( and programming in general ).  So Laravel is responsible for my PHP adventure. And not just PHP. My knowledge about obligatory design patterns and whole object-oriented paradigm was missing some glue. Sure, thanks to previous experience with JS, in which I had to read about whole programming history and evolution of modern languages, I can flow between PHP code with no real struggle.

And of course, beautifully structured and designed Laravel is a joy to read without writing a single line of code - like a great novel. Class bases languages and frameworks like Laravel helps me to write better organized and more secure code - which is standard for server side applications. So my approach to Laravel is not just from the point of someone who wants to write web-applications and learn API. Through Laravel, I am making progress as a programmer, and I hope I'll be able to contribute to Laravel core soon :)

So this post somehow represents a long introduction to my future writings about Laravel internals, so stay tuned and thanks for reading.


10/22/2013

REST cheat sheet

I created a simple cheasheet table, like every day reminder for creating beautifull rest API-s. So, if you have experience with old PHP routing style in the form of:
"http://host/resource /?id=some_id"

it is time to refresh your skills by moving to more modern approach. Fortunately, REST (Representational state transfer) is supported in all new frameworks like ExpressJS or PHP Laravel.
So this table can help because it can be sometimes confusing to remember which verb belongs to which path.

Here it is:


Thanks for visiting my blog.
Miro

10/21/2013

How to properly understand Javascript language PART 1 ?

Hello;

My first programming language was Javascript. Learning JS without previos knowledge of programming theory ( paradigms, history and language background ) was a very painful process, full of pitfalls and roaming in the dark.  As I can see, a lot of people had a same experience. From my point of view it is because  in JS it is relatively  easy to write applications that looks like a real applications - with the help of large number of  libraries that provides usefull abstractions in the form of their "easy to learn" API.  Canonical example is jQeury - with a minimal code you can have reference to DOM object, without knowing what is happening in the back:

    //
    var elem = $("div")
    //

I am not saying that abstractions are evil, and that we should avoid them. It should be a nightmare to write code without them. After all with the help of abstractions, we are not writing assemby anymore, or in the case of jQuery, cool animations. I want to say that when learning language  starting with libraries like jQuery can cause  unnecessary confusion, which is hard to correct.

This is even more the case with JS, because of it‘s weird combinations of paradigms and idioms. For example, concept of closure  has become trademark of a language, that is very hard to pick without a knowledge about its context, root and origin. To proof, term closure is one of the most searched programming term online, with blogs and even whole sites dedicated to it.
People are really having problem to digest closure. It is not a surprise, because it is one of the hardest programming concept that exist.

After years of struggling with JS I created my mental model about what is Javascript. Of course, it is not just a theory. I am a programmer and the whole point of this post is to better understand Javascript so I can express my self with code.

So lets examine some of the main bulding blocks of JS.

I‘ll start with syntax, since it is very natural to start with when learning new language. Javascript belongs to so called "curly-braces" family of languages, which is mostly influenced by C.
Take a look at the following examples:
    //
    var i;
    for ( i = 0; i < 5, i++){
          console.log("hello");
    };
    int i;
    for ( i = 0; i < 5, i++){
          printf("%s\n","hello");
    };
    //

These two examples are identical, except one cosmetic difference. To write to output, Javascript uses console.log method, which is specific to browser environment, and C uses printf. Their syntatic similarity can also be seen  through code formating that I use in this blog. Both loops are formatted using same pre tag ( <pre class = "brush:js">), which is JS specific. But the output is still well formed, except some minor color differences.  Looking deeper in the languages syntax, there is very, very close relationship between them. I don't want to spend too much time dealing with that topic, since it is covered in more details on other places. To start with syntax comparison read a great Wiki articles: Comparison of programming languages syntax and List of programming languages by type.

The main takeaway from this is: Take some to learn basis of C programming language.  There are tons of great resources and tutorials online. You'll be surprised how much is Javascript influenced by C. In the beginning that influence can be seen as only syntatical, but with experience you'll see how much  have you missed. I became enlightened after learning C.

And that is just a beginning. In the future posts I'll cover other important Javascript  paradigms - first object and then functional.

Miro.


9/16/2013

Linux system calls - fork,exec and pipes.

These days I am passionate about network programming concepts, in order to fully understand Nodejs stack.
I created a small program to demonstrate canonical usage of basic linux system calls - fork, exec and pipes. These calls are used in most network applications and servers. It is heavily commented. Sorry for the code formatting, it is syntax highlighter issue.

#include
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


// canonical example of fork,pipe and exec.
// it is heavily commented

// main program
int main (int argc, char ** args)
{
    // pipe
    int p[2];
    char buf[5]="\0";
    int pid;

    // do we have a fork ?
    if (!fork()){
        // write to one end of pipe
        write(p[1],"Child writes to pipe\n",22);

        // open a file
        int fd = open("one.js",O_RDWR);
        // read from that file
        read(fd,buf,70);

        //close file descriptor
        close(1);
        // replicate closed descriptro
        int i = dup(0);
        // print usefull message
        printf("Value of fd is: %d\n",i);

        // open new program, and provide some arguments
        execlp("./one","one",buf,NULL);

        // don't forget to exit child process and close open file descriptor
        exit(0);
        close(fd);
    }else{
        printf("Parent reading pipe");
        // read from a pipe
        read(p[0],buf,5);
        // print a pipe content
        printf("%s\n",buf);
        // wait for a child to exit
        wait(NULL);
    }
   return 0;
}
//

Thanx for visiting my blog
Happy Coding :)

9/05/2013

Network programming with sockets

I have to admit, I've moved away from Javascript , and I am spending most of my time in C/C++ together with Unix/Linux programming.
One of awesome things in compiled land :) are native kernel support for socket interface. In case you don't know what are sockets check out this link. Sockets are the basis of Internet, and It is very usefull to become familiar with them. Socket header files are written in C, but there are implementations for all modern languages. Sockets represents low level layer of network stack.
This is my simple implementation of server socket, written in C:

//
#include 
#include 
#include 
#include 
#include 
#include 
#include 

const char message[] = "Yuhuuuuu. Hello From The Server\n";
int main(int argc, char *argv[]) {

    int simpleSocket = 0;
    int simplePort = 0;
    int returnStatus = 0;
    struct sockaddr_in simpleServer;

    if (2 != argc) {

        fprintf(stderr, "Usage: %s \n", argv[0]);
        exit(1);

    }

    printf("%s\%s\n","Listening of port: ",argv[1]);

    simpleSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (simpleSocket == -1) {

        fprintf(stderr, "Could not create a socket!\n");
        exit(1);

    }
    else {
     fprintf(stderr, "Socket created!\n");
    }

    /* retrieve the port number for listening */
    simplePort = atoi(argv[1]);

    /* setup the address structure */
    /* use INADDR_ANY to bind to all local addresses  */
    bzero(&simpleServer, sizeof(simpleServer));
    simpleServer.sin_family = AF_INET;
    simpleServer.sin_addr.s_addr = htonl(INADDR_ANY);
    simpleServer.sin_port = htons(simplePort);

    /*  bind to the address and port with our socket  */
    returnStatus = bind(simpleSocket,(struct sockaddr *)&simpleServer,sizeof(simpleServer));

    if (returnStatus == 0) {
     fprintf(stderr, "Bind completed!\n");
    }
    else {
        fprintf(stderr, "Could not bind to address!\n");
 close(simpleSocket);
 exit(1);
    }

    /* lets listen on the socket for connections      */
    returnStatus = listen(simpleSocket, 5);

    if (returnStatus == -1) {
        fprintf(stderr, "Cannot listen on socket!\n");
 close(simpleSocket);
        exit(1);
    }

    while (1)

    {

        struct sockaddr_in clientName = { 0 };
 int simpleChildSocket = 0;
 int clientNameLength = sizeof(clientName);

 /* wait here */

        simpleChildSocket = accept(simpleSocket,(struct sockaddr *)&clientName, &clientNameLength);

 if (simpleChildSocket == -1) {

            fprintf(stderr, "Cannot accept connections!\n");
     close(simpleSocket);
     exit(1);

 }

        /* handle the new connection request  */
 /* write out our message to the client */
 write(simpleChildSocket, message, strlen(message));
        close(simpleChildSocket);

    }

    close(simpleSocket);
    return 0;
}
//
Happy Coding.