Monday, 8 December 2014

Model-View-Controller (MVC)

Model-View-Controller (MVC)

Let’s get a high-level overview of how Laravel applications work. You might have noticed that the standard Laravel application structure has an application directory called app/ with three subdirectories: models/views/, andcontrollers/. This is a hint that Laravel follows the model-view-controller (MVC) architectural pattern, which enforces a separation between “business logic” from the input and presentation logic associated with a graphical user interface (GUI). In the case of Laravel web applications, the business logic typically consists of data models for things like users, blog posts, and the GUI is just a web page in a web browser. The MVC design pattern is very popular in the web development space.
There are three components to the MVC pattern:
  • The model - The domain that your software is built around. Models are based on real-world items such as a person, bank account, or product. If you were building a blog, your models might be post and comment. Models are typically permanent and will be stored outside the application, often in a database. A model is more than just data; it enforces all the business rules that apply to that data. For example, if a discount shouldn’t be applied to orders of less than $10, the model will enforce the constraint. This makes sense; by putting the implementation of these business rules in the model, we make sure that nothing else in the application can make our data invalid. The model acts as both a gatekeeper and a data store.
  • The view - The visual representation of a model, given some context. It’s usually the resulting markup that the framework renders to the browser, such as the HTML representing the blog post. The view layer is responsible for generating a user interface, normally based on data in the model. For example, an online store will have a list of products to be displayed on a catalog screen. This list will be accessible via the model, but it will be a view that accesses the list from the model and formats it for the end user. Although the view may present the user with various ways of inputting data, the view itself never handles incoming data. The view’s work is done once the data is displayed.
  • The controller - The coordinator that provides the link between the view and the model. The controller is responsible for processing input, acting upon the model, and deciding on what action should be performed, such as rendering a view or redirecting to another page. Continuing the blog example, the controller might look up the most recent comments for a post (the model) and pass them to the view for rendering.

Components of Laravel

A typical Laravel application consists of the above mentioned MVC components, as you can see below:

When interacting with a Laravel application, a browser sends a request, which is received by a web server and passed on to the Laravel routing engine. The Laravel router receives the request and redirects to the appropriate controller class method based on the routing URL pattern.
The controller class then takes over. In some cases, the controller will immediately render a view, which is a template that gets converted to HTML and sent back to the browser. More commonly for dynamic sites, the controller interacts with a model, which is a PHP object that represents an element of the application (such as a user, blog post) and is in charge of communicating with the database. After invoking the model, the controller then renders the final view (HTML, CSS, and images) and returns the complete web page to the user’s browser.
Laravel promotes the concept that models, views, and controllers should be kept quite separate by storing the code for each of these elements as separate files in separate directories. This is where the Laravel directory structure comes into play.
Design patterns such as MVC are created to make a developer’s life easier. This is where Laravel scores over plain PHP which doesn’t follow any sort of paradigm. If this discussion seems a bit abstract right now, worry not! After you start working with Laravel, you won’t even realize that you are working in a design pattern. It all becomes natural to you after a while.

Introduction to Laravel Framework

Introduction to Laravel Framework

This book is about Laravel, a web application development framework that saves you time and effort and makes web development a joy. Laravel has shaken up the PHP community in a big way - especially when you consider that version 1.0 of Laravel was only a couple of years ago. It has been generating a lot of buzz with the promise of making web applications fast and simple to create. Using Laravel, you can build and maintain high-quality web applications with minimal fuss.
Certain parts of a web application development process can be a repetitive, boring task. Laravel lets you focus on the fun stuff - the crux of your web app - while easing the pain of the repetitive bits. In doing so, it provides high-level abstractions of common web development patterns, convenient shortcuts for frequent programming tasks, and clear conventions for how to solve problems.

Architecture of Laravel Applications

Laravel is referred to as a “full stack” framework because it handles everything from web serving to database management right down to HTML generation. A vertically integrated web development environment can provide a better experience for the developer.
The typical developer interacts with Laravel through a command-line utility that generates and manages the Laravel project environment. Laravel comes with an excellent command-line tool named Artisan that can be used to generate skeleton code and database schema stubs. Artisan handles everything from database schema migration to asset and configuration management.

Convention Over Configuration

One of the interesting features of Laravel is that it imposes some fairly serious constraints on how you structure your web applications. Surprisingly, these constraints make it easier to create applications - a lot easier. Let’s see why.
Laravel differs from other vertically integrated environments in its strong preference for convention over configuration. Whereas some Java, Python or PHP frameworks often require lots of XML configuration, Laravel requires almost none (or perhaps only a few lines of PHP) to get started. This aversion to configuration files makes for a very distinctive and recognizable code structure that is the same across all Laravel apps.

One Project Structure To Rule Them All!

It comes as no surprise that all Laravel projects have essentially the same directory structure - one in which every file has its designated place. By gently forcing this directory structure upon developers, Laravel ensures that your work is semi-automatically organized the “Laravel way”.
Figure 1.1 shows what the Laravel project directory structure looks like:
As you can see, this standard directory structure consists of quite a few subdirectories. This wealth of subdirectories can be overwhelming at first, but we’ll explore them one by one. Most of your work will happen in the app/ folder, but here’s a basic rundown on the function of each of the files and folders:
Top-level FoldersPurpose
/app/Contains the controllers, models, views and assets for your application. This is where the majority of the code for your application will live. You will be spending most of your time in this folder!
/public/The only folder seen to the world as-is. This is the directory that you have to point your web server to. It contains the bootstrap file index.php which jump-starts the Laravel framework core. The public directory can also be used to hold any publicly accessible static assets such as CSS, Javascript files, images and other files.
/vendor/A place for all third-party code. In a typical Laravel application, this includes the Laravel source code and its dependencies, and plugins containing additional prepackaged functionality.
As mentioned above, /app is where all the fun happens, so let’s have a deeper look at the structure of this directory.
Figure 1.2 shows the /app folder in detail:
File/FolderPurpose
/app/config/Configure your application’s runtime rules, database, session and more. Contains a number of config files for changing various aspects of the framework. Most of the config files return associative PHP arrays of options.
/app/config/app.phpConfiguration for various application level settings, i.e. timezone, locale, debug mode and unique encryption key.
/app/config/auth.phpConfiguration that controls how user authentication will be performed in the application, i.e. authentication driver
/app/config/cache.phpIf the application utilizes caching to speed up response time, this is where you configure the feature.
/app/config/database.phpContains relevant configuration information for the database, i.e. default database engine and connection information.
/app/config/mail.phpConfiguration for e-mail sender engine, i.e. SMTP server, From: header
/app/config/session.phpConfiguration that controls how user sessions are managed by Laravel, i.e. session driver, session lifetime.
/app/config/view.phpMisc. configuration settings for templating systems.
/app/controllersContains the controller classes that are used to provide basic logic, interact with data models, and load view files for your application.
/app/database/migrations/The migrations folder contains PHP classes which allow Laravel to update the Schema of your current database while keeping all versions of the database in sync. Migration files are generated using the Artisan tool.
/app/database/seeds/The seeds folder contains PHP files which allow Artisan to populate database tables with reference data.
/app/lang/PHP files containing arrays of strings to enable easy localization of the application. By default the directory contains language lines for pagination and form validation for the English language.
/app/models/Models are classes that represent the information (data) of the application and the rules to manipulate that data. In most cases, each table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models.
/app/start/Contains custom settings related to the artisan tool as well as global and local context.
/app/storage/The storage directory is used as temporary file store for various Laravel services such as sessions, cache, compiled view templates. This directory must be writable by the web server. This directory is maintained by Laravel and you need not tinker with it.
/app/tests/The tests folder provides a convenient location for you to keep your application Unit tests. If you are using PHPUnit, you can execute all tests at once using the Laravel Artisan tool.
/app/views/The views directory contains your HTML template files used by controllers or routes. Note that you should place only the view template files in this location. Other static assests such as stylesheet, javascript and image files should be placed in the /public folder instead.
/app/routes.phpThis is your application’s routing file which holds routing rules that tells Laravel how to connect incoming requests to route handler closure functions, controllers and actions. This file also contains declarations for several events including error pages, and can be used to define view composers.
/app/filters.phpThis file contains various application & route filter methods that alter the outcome of your application. Laravel has some pre-defined filters for access control and XSS protection.
A lot of thought has gone into establishing and naming the folders, and the result is an application with a well structured file system.


Simple CRUD in Laravel Framework

Creating, reading, updating, and deleting resources is used in pretty much every application. Laravel helps make the process easy using reso...