Reputation: 11452
Recently I have started working with Codeigniter
framework in order to develop RESTFul
web service for mobile application.
As I was looking at various tutorials on web sites and on youtube, I found that the concept of a Model
is being used differently in PHP application context.
How differently?
Well, as I always thought Model classes should look like,
Cat.php
<?php
class Cat {
// Class variables
private $colour;
public __construct() {
$colour = 'Brown';
}
// Getters and Setters
public function getColour() {
return $this->colour;
}
public function setColour($newColour) {
$this->colour = $newColour;
}
}
?>
but, while searching for good tutorials over the internet I found that people are just using functions that has access to the database for data and returning it to Controller
.
I haven't seen any one writing normal classes in Model (If you are Java person then, we call it POJO)
Now, What I entailed after reading and watching these tutorials that,
In context of PHP application frameworks, The Model classes are connectors to the database which returns the application related data upon query. In language of SQL people we call it,
CRUD functions
In web application created by taking base of Codeigniter like framework, where the MVC pattern is used to design an application. The Model classes are the one which will have functions that connects application to the database and returns the data, as well as helps to perform all CRUD operations on application's database.
Upvotes: 1
Views: 957
Reputation: 5692
Well, if you have used C# or Ruby, there you can find a good way to apply the MVC pattern. In PHP, in my opinion, people sometimes are confused about the terms. The way I use the MVC pattern in PHP is like the following:
CONTROLLER
class UserController {
private $repo;
public function __construct() {
$this->repo = new UserRepository(); // The file which communicates with the db.
}
// GET
// user/register
public function register() {
// Retrieve the temporary sessions here. (Look at create function to understand better)
include $view_path;
}
// POST
// user/create
public function create() {
$user = new User($_POST['user']); // Obviously, escape and validate $_POST;
if ($user->validate())
$this->repo->save($user); // Insert into database
// Then here I create a temporary session and store both the user and errors.
// Then I redirect to register
}
}
MODEL
class User {
public $id;
public $email;
public function __construct($user = false) {
if (is_array($user))
foreach($user as $k => $v)
$this->$$k = $v;
}
public function validate() {
// Validate your variables here
}
}
Upvotes: 5