Demo of MVC for BarCamp Cameroon 2010

I have not blogged for a while;I have been busy ;).This blog post presents the partial codes for the presentation I did at BarCamp Cameroon.

Barcamp Cameroon(barcamp.org/BarCampCameroon2010#BarCampCameroonProgram)
passed 2  weekends ago and I must say it was an amazing event, the presentations and the people and  the energy!.
Check for My the presentaion here: MVC
I did a preach on MVC(Model View Controller), how it can ease development across  platforms:Web,Enterprise and Mobile:
Web,Enterprise and Mobile
I am to demonstrate that for php using Kohanaphp;don’t ask why….I just love the framework.You can read the previous post if you are not using a framework and wish to know what a framework is.

I don’t like assumptions,I will wish to make it common for everybody but I am force to!.:).
I shall assume or require  the following:
1.You have some familiarity with php
2.You  have a basic familiarity with the kohanaphp framework(I use 2.3.1),
If you are interested in the framework, then check my other post about 10 reasons, ok!.
No more talking and business….GO!.

We need to demonstrate the use  of Model View Controller (MVC) in php using the Kohana php framework.
It is a simple form with user Email and a Message to be submitted,validated and stored to the database.

DATA:

Model:
Create a php file call it, contact.php drop it under the application folder/model and copy the following code to it:

<?php  defined(‘SYSPATH’) or die(‘No direct script access.’);
/*
Model(which is a class) and we are using ORM(active records)
With ORM,since our Model’s name is Contact, we are supposed to have a table in the database with name
contacts(with the ‘s’).Table with fields (id,email,message)
@author Njie-litumbe.L.Nara ======= njielitumbe@gmail.com
@www.afrovisiongroup.com  ========== njielitumbe.livejournal.com
*/
//Considering we have a table called contacts in the database
class Contact_Model extends ORM{
}
Save it!.

LOGIC:
Controller:
Create another php file call it,contact.php drop under the controller folder, copy and paste the following code:

<?php defined(‘SYSPATH’) or die(‘No direct script access.’);

/**

@author Njie-litumbe.L.Nara ======= njielitumbe@gmail.com
@www.afrovisiongroup.com  ========== njielitumbe.livejournal.com
**/
class Contact_Controller extends Controller{

public function _construct()
{
parent::_contruct();
}

public function index(){

/*We are to take the input from the user Through the view,
the Controller does all the validation ,if there is an error it sends
the notice of the particular errror to the view, if there is no error,
it sends the entry to the model,the model actuates the change by saving it to the data              base.*/

//Let us define all our views without redering,I use ‘view of views’;
$view = new View(‘view_template’);

//We pass the header.php to the view_template
$view->header = new View(‘header’);
//We set the title of the header.php file
$view->header->title = ‘Contact Info’;
//we pass the footer.php to the view_template
$view->footer = new View(‘footer’);

//we pass to the content of the view_template contact_view for the main business
$view->content = new View(‘contact_view’);

$view->content->heading = ‘Contact Info | MVC by Nara’;

//lets get the form fields we intend to use ready
$field = array
(‘message’=>”,’email’=>”);

//We set out notice variable to NULL
$notice = “”;
$post = $this->input->post();
//we then copy the form fields into an error variable, each form field has an error association
$errors = $field;

//VALIDATION……
//check if the form is submitted ,
if($post){

//we call the validation Library to do the validation for us, Thank you frameworks 😉
$post = new Validation($_POST);
//we add rules to the data input
//We filter whitespaces at the start and end of the input
$post->pre_filter(‘trim’);
//All our fields are required
$post->add_rules(‘*’,’required’);
//We make sure the email is a valid one
$post->add_rules(’email’,’valid::email’);

//We do our stuffs when we pass the validation; We want to store in the database!.
if($post->validate())

{
//instantiate the object, to start using the model
//I am using ORM
$store = ORM::factory(‘contact’);
$store->email = $_POST[’email’];
$store->message =$_POST[‘message’];
$store->save();
//Lets make sure the data is stored in the database, then send the notice to the user
if($store->save()==true){

$notice .=”Thanks , your Information is Saved!”;
} else{
$notice .= die(‘Trouble saving your data,Try again!’);
}

}
//if the validation fails then there where errors, Let us report the errors
else{

$notice.=”There where some Errors: <br>”;
//Let us repopulate the form
$field = arr::overwrite($field, $post->as_array());

//Lets set the corresponding errors,as we defined in the validation and stored in the                  field_errors file

$errors = arr::overwrite($errors,$post->errors(‘field_errors’));

foreach($errors as $key=>$post)
{
$notice .= $post.”<br>”;
}

}

}
//We set the notice then finally render once.
$view->content->set(‘notice’,$notice);

$view->render(true);

}

}


PRESENTATION:

The View:
We shall be using ‘views of views’ forget the name just do as follow:
All the following files are droped under the application/view folder.
Create another php file, call it header.php and past the following code in it:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<link rel = “stylesheet” type = “text/css” href=”<?=url::base()?>css/my_css.css” />
<title><?=$title?></title>
</head>

<body>

Create another and call it footer.php and paste this:
</body></html>
Create again another call it  contact_view.php and paste the following code:

<h1><?= $heading?></h1><br>

<?php echo form::open(‘contact’);?>

<?php
if(!empty($notice)){
echo “<p  style=’background-color:#FFFF66;border:1px solid #FFFF00;font-weight:bold;width:97%;padding:5px;’>”.$notice.”</p>”;
}
?>

<?php echo form::label(’email’,’Your Email*’);?>
<?php echo form::input(’email’,@$_POST[’email’]).”<p>“;?>

<?php echo form::label(‘message’,’Your Message*’);?>
<?php echo form::textarea(‘message’,@$_POST[‘message’]).”<p>”;?>

<?php echo form::submit(‘submit’,’Send Info!’);?>
<?php echo form::close();?>

Create another file call it  view_template.php and paste the following code into it:

<?php echo $header;?>
<?php echo $content;?>
<?php echo $footer;?>

Create the Custom Error Messages:
create another php file, call it field_errors.php drop under application/i18n paste the following:
<?php
$lang=array(
‘message’=>array(
‘required’=>’The message field is required!’,
),
’email’=>array(
‘required’=>’The email field is required!’,
’email’=>’The email you provided is not a valid email!’,
‘default’=>’The email field has a problem!’,
),);

Create … NO! We are done creating…;).
But if you need style then Create a css file call it my_css.css and drop under the a CSS folder under the maindirectory(It is not there create it!).
Paste the following code:
/* CSS Document */

body                       { font:12px/1.3 Arial, Sans-serif; }

/*css for our form entries*/
form                       { width:380px;padding:0 90px 20px;margin:auto;background:#f7f7f7;border:1px solid #ddd; }
label                      { cursor:pointer;display:block; color:#00EE00; }
input[type=”text”]         { width:300px;border:1px solid #999;padding:5px;-moz-border-radius:4px; }
textarea[name=”message”]   { width:300px;border:1px solid #999;padding:5px;-moz-border-radius:4px; }
input[type=”text”]:focus   { border-color:#777; }

/* submit button */
input[type=”submit”]       { cursor:pointer;border:1px solid #999;padding:5px;-moz-border-radius:4px;background:#eee; }
input[type=”submit”]:hover,
input[type=”submit”]:focus { border-color: #333;background: #ddd ;}
input[type=”submit”]:active{ margin-top:1px; }

Run the codes!.

This is What you get:

This is what you get!

The Demo is complete.The use of Model View Controller has been brought out well.
Now, If I have to add a service to display the number of users who have sent messages shorter than 20 words  and get a chart for the different message length I will need to add just a function(method) under the class controller and a new view file under the View folder.
I can choose to change how I wish the user to see the information display,,,,I change the view. If there is a new Logic I add a function under the controller. For a new table or additional data I create a new Model class(a simple class as demonstrated above).
I used ORM I am guilty….I just used an engine saw to kill an ant ;).

The other codes for the iphone/Android without even the sdk:Test on your Android/iphone, Safari /Chrome.

I’ll see you soon.

Next Blog post: The Nature of Objects in Object Oriented Programming.

tweetI tweet

Leave A Comment

Your email address will not be published.