Models - adampatterson/Dingo-Framework GitHub Wiki
What Are Models?
Models in Dingo are designed to access and work with information in your database. For example you could have a model that has functions for creating, updating, and deleting users from your database. Models can also be used for puposes other than database access if you want.
Dingo does not require you to use models in your application, but it is highly recommended that you do.
Create A Model
Create a new PHP file at application/models/user.php
. This will be our model. Below is the basic structure of a model.
<?php
class user_model
{
// Model functions go here
// Notice that the class is called user_model because this is the `"user.php"` model
}
Let's say we want our model to manage users in our database, so let's add a function to fetch a user's data from the database. For more information on Dingo's databasing functions please see that section of the documentation.
<?php
class user_model
{
public function get($name)
{
// Return results from a query
return db('users')->select('name','=',$name);
}
}
Use It
Now to load your model so you can use it do this in your controller:
$user = load::model('user');
You could then use the functions in the user_model
class via the $user
variable.
$evan = $user->get('evan');
Parent Models
In Dingo, it is possible to make model classes extend from other model classes. For example you may have a model that looks like this:
<?php
class base_model
{
public function get($table,$column,$value)
{
return db($table)->select($column,'=',$value);
}
}
Then, you could have another model that extends from your parent model so it can access the get()
method.
<?php
load::parent_model('base');
class another_model extends base_model
{
public function id($name)
{
$user = $this->get('users','name',$name);
// User found
if(isset($user[0]))
{
return $user[0]->id;
}
// User not found
else
{
return FALSE;
}
}
}
You may then use this model like so:
$id = $user->id('evan');
Parent models may have their own parent models as well.