twitterfacebookgoogle plusrss feed

Pages

Friday, March 28, 2014

How to create file and directory structure for MVC


You will find dozens of free and opensource MVC fameworks (Zend, CodeIgniter, CakePHP are some of them) around you, loaded with hundred of features so on this point making your own MVC is not a good idea. But for practising purposes I will tell you how MVC works and how to build directory and file structure for your very own MVC.

In old fashioned web page/application we handle user input, manipulates or use databases and then redirect user to beautifully organized results suitable to user input. All this activity occurs in single page, its okay if we are working on small application where much business logic isn't repeated. But in enterprise application this approach possibly make duplications in the code.

So what should we do if we are going to build enterprise level application.


MVC (Model-View-Controller)

It is a software pattern or architecture divided and interconnected into three parts, overridden old fashioned web page/application. Controller takes the user input, manipulates and convert input to command and send the formatted user commands to Model. Model is collection of logics and a place where we run database operations and send back required information to Controller, Controller then injects all user requested information in to the View. View might be collection of standard HTML commands, diagrams, charts, Javascript, CSS and any possible client side script. Take a look at the following flow chart it will help you to better understand MVC architecture.





Note: Kindly pass comments if you found any logical problem in flow chart, your comments will worth me a lot.

Break apart

Model: As per Controller request informs associated Controller and View about changes, so View change its representation and Controller update commands.

View: Controls the representation according to Controller commands.

Controller: Manipulate user input and send commands to Model to update model's state. Compile and inject the final out put to the View.


MVC files and folders structure

You need 4 folder and 2 files on the root

1) model (dir)
2) view (dir)
3) controller (dir)
4) engine (dir)

1) index.php



2) .htaccess

"model" directory contains all Models (files) or project.

"view" directory contains the files for the project used as front-end. User will serve and see these files.

"controller" directory contains Controllers (files) for the project

MVC has three basic files, main Controller, main Model and main View file known as engine for your MVC framework. These three files extends by all other Controllers, Models and Views. Besides these files you may also need helpers and libraries to be imported later in the project also placed in "engine" directory.

"index.php" file is very crucial, this is main switch to start your framework. Be careful while approaching professional level. Things started at this point will be available to all our project.

".htaccess" optional file. Just to beautify your URL to make it search engine friendly. Without this file your framework will function properly but I recommend to use it to make your project search engine friendly.

Come slowly


Come slowly, Eden
Lips unused to thee.
Bashful, sip thy jasmines,
As the fainting bee,
Reaching late his flower,
Round her chamber hums,
Counts his nectars -alights,
And is lost in balms!

Wednesday, March 26, 2014

Uncaught TypeError: Property '$' of object [object Object] is not a function


If you are getting this error in WordPress then remember that WordPress loads jQuery with noConflict mode or any other application which loads with noConflict mode cause this error, you will no longer able to use jQuery shortcut ($) any more in this mode. On this point you have to use jQuery (case sensitive) instead jQuery shortcut $ (dollar sign) and if you want to use $ sign in code block than must pass $ (dollar sign) as function parameters;

jQuery(function($) {
    // now are able to use $ sign or jQuery
});

Tuesday, March 25, 2014

Use other libraries with jQuery using $.noConflict()


Just like jQuery, many other Javascript libraries uses $ (dollar sign) as a function. Using other Javascript library on the same page might cause error. So on the safe side, jQuery offers jQuery.noConflict() or $.noConflict; it restores all old references which are saved during jQuery initialization.

How to use it? Well, simply put jQuery.noConflict() at the top of your script. If you are experiencing "Uncaught TypeError: Property '$' of object [object Object] is not a function" error in console; its mean $ (dollar sign) is conflicting with other javascript library, put $.noConflict() on the top of the script. Still same error? no problem, in noConflict mode you cannot use shortcut of jQuery ($) use jQuery and pass $ (dollar sign) as function parameter. By including the $ in parenthesis after the function call you can then use this jQuery shortcut ($) within the code block. 

jQuery(document).ready(function($) {
   // your code here with $ sign
});

or 

jQuery(function($) {
   // your code here with $ sign
});

Sunday, March 23, 2014

How the Universe ends?


And when the sky will split it will become rose like red hide. (Holly Quran, Chapter: Al-Rahman, Verse: 37)

Image downloaded from http://en.wikipedia.org/wiki/File:Formalhaut_b.jpg
Reference: http://en.wikipedia.org/wiki/Hubble_Space_Telescope#Equipment_failure 

Evidence that the Universe began with the Big Bang is quite compelling. 13. 8 billion years ago, the entire World was compressed right into a microscopic singularity of which grew exponentially in to the vast cosmos all of us see today. But what does the longer term hold? How will the Universe stop?

Astronomers are pondering the best fate with the Universe for 1000s of years. Within the last century, cosmologists thought to be three outcomes to the end regarding everything, and it also all depended about the critical density with the Universe. In the event that this crucial density had been high, then there was clearly enough communal gravity to be able to slow and at last halt the expansion. Billions regarding years sometime soon, it would certainly then fall in upon itself yet again, perhaps making another Huge Bang. This is known as a closed Galaxy, and the last result could be the Big Crisis. Should the critical thickness was reduced, then at this time there wouldn’t be adequate gravity to hold on to things with each other. Expansion would keep on forever as well as ever. Personalities would expire, galaxies will be spread separate, and every thing would cool-down to the background temperature on the Universe. This really is an available Universe, and the finish is known as the Big Freeze.

Thursday, March 20, 2014

Get reference from URL for MVC framework


Look at following URL

http://www.example.com/records/dvds/10

While creating MVC framework you have to follow the URL for reference. In above URL "records" is class or controller name. Controller is used to accept user input, after collecting data it prepare commands for Model and View. Reference to above-mentioned URL, "dvds" is a method of Controller "records" and "10" is parameter of method "dvds".

Note: URL is rewritten using .htaccess (check this post)

Now the question is how we will split the URL to get controller, its method and parameter for method. 

First get the URL by 

$route = $_GET["route"]; // or what ever you passed in .htaccess

Split the $route with "/"

list($class, $method, $param) = explode('/', $route); 

Now $routes is array holds controller name and its method and parameter if passed. 

if (is_file('controller/' . $class . '.php')) {
    $file = 'controller/' . $class . '.php'; // get the file of the Controller
}

Now you have, Controller, Controller file (where class or Controller written), method and parameter. Remember all three parts of URL (Controller, Method and Parameter) will not be passed every time, so be careful when approaching higher level.

Wednesday, March 19, 2014

A charm invests a face (Emily Dickinson)


A charm invests a face
Imperfectly beheld.
The lady dare not lift her veil
For fear it be dispelled.

But peers beyond her mesh,
And wishes, and denies,
Lest interview annul a want
That image satisfies.

Tuesday, March 18, 2014

.htaccess for MVC


In MVC routes are normally sent through query string formatted using .htaccess. You are passing a query string to index.php i.e. domain.com/index.php?route=records/dvds/10 transform into domain.com/records/dvds/10. What you have to do is create a new file .htaccess using any supported editor (netbeans will be best, remember notepad of windows do not support a file with no file name) and put following lines into the file, save and place this file in root of the folder where you want to create operational MVC.


RewriteEngine On

RewriteCond %{REQUEST_FILENAME}% !-d
RewriteCond %{REQUEST_FILENAME}% !-f
RewriteCond %{REQUEST_FILENAME}% !-l

RewriteRule ^(.*)$ index.php?route=$1


It will successfully tranforme junky query string into nice looking url. The first part of url is considered a controller or class, the second part after front slash "/" is known to be method and the last one is parameters for the method. If "route" in query string is records/dvds/10 (looks like domain.com/records/dvds/10) you have to explode this string on "/" and it will returns an array contains three pockets, 0=>records (controller or class), 1=>dvds (method of records), 2=>10 (parameter of records).

Monday, March 17, 2014

QSA or Query String Append



QSA is flag used in .htaccess to append query string in traditional format into formatted or over written url after the URI has been rewritten. For example you are rewrite url from http://www.example.com/index.php?id=foo&user=bar to http://www.example.com/foo/bar and now you want to pass traditional query string to this over written url like http://www.example.com/foo/bar/?action=success then you have to declare following rule in .htaccess like RewriteRule ^([A-Za-z0-9]+)\/([A-Za-z0-9]+)$ index.php?id=$1&user=$2 [QSA]


Sunday, March 16, 2014

Rain before Dawn (F. Scott Fitzgerald)



The dull, faint patter in the drooping hours
Drifts in upon my sleep and fills my hair
With damp; the burden of the heavy air
Is strewn upon me where my tired soul cowers,
Shrinking like some lone queen in empty towers
Dying. Blind with unrest I grow aware:
The pounding of broad wings drifts down the stair
And sates me like the heavy scent of flowers.

I lie upon my heart. My eyes like hands
Grip at the soggy pillow. Now the dawn
Tears from her wetted breast the splattered blouse
Of night; lead-eyed and moist she straggles o'er the lawn,
Between the curtains brooding stares and stands
Like some drenched swimmer -- Death's within the house!