element
Models
Overview
Introduction
Within element, models are purely used for database access.
We use object relational mapping (ORM), creating a class that represents a table in the database
At the time of writing, there is no custom mapping function: model properties should directly represent column names
Structure
The namespace is element/mvc.
To use models, simply create a class that extends Models, then add properties as publicly available variables
Models don't use a suffix of Model, as Controllers do. To create a 'test' model, simply name the file Test.php and name the class Test.
Let's create a table to better understand how models work.
First, set up a MySQL or MariaDB database named element. Then run the query below
SQL
CREATE TABLE 'element'.'test' (
'id' INT NOT NULL AUTO_INCREMENT,
'name' VARCHAR(45) NULL,
'email' VARCHAR(45) NULL,
PRIMARY KEY ('id'));
Model
namespace element/mvc;
class Test extends Model {
/**
* @var integer
*/
public $id;
/**
* @var string
*/
public $name;
/**
* @var string
*/
public $email;
}
Note that although we have used PHPDoc here for notation, it is not needed by element
Create
Instantiate our test class
$test = new Test();
Populate the 'columns' in an OOP way
$test->name = "Davey Jones";
$test->email = "davey.jones@blackpearl.com";
Because we specified earlier that the 'id' key was an auto-incrementing primary key, we shouldn't explicitly set it at create.
When we save the model, we have an optional parameter. If passed, our $test object will have the value of
its primary key returned and saved to the class held in our $test variable.
If we call echo $test->id, we should see '1' output to the screen.
Saving a model will also return true if successful, so you can test for failure.
Radical daredevil mode
$test->save(); // pass true to set id
Fairly safe
$test->save(true);
if(isset($test->id)) {
echo $test->id;
}
Super careful, actually wearing a helmet whilst typing
$errorMessage = "Something's wrong! Something's amiss!";
try{
if($test->save(true)) {
echo $test->id;
} else {
echo $errorMessage;
}
} catch(Exception $ex) {
echo $ex->getMessage();
}
Putting it all together
$test = new Test();
$test->name = "Davey Jones";
$test->email = "davey.jones@djlocker.com";
$errorMessage = "Something's wrong! Something's amiss!";
try{
if($test->save(true)) {
echo $test->id;
} else {
echo $errorMessage;
}
} catch(Exception $ex) {
echo $ex->getMessage();
}
Retrieve
To retrieve a model, we send a paramaterized query to fetch the data. By retrieving data in this way, we begin to mitigate the potential for SQL Injection.
Methods for retrieving models
- getOne
- getMany
- getById
- getAll
getOne
$email = "davie.jones@djlocker.com";
$testUser = Test::getOne("email = :email", [
":email" => $email
]);
getMany
$emailSnippet = 'davie%';
$testUsers = Test::getMany(
'email LIKE :emailsnippet', [
':emailsnippet' => $emailSnippet
]);
// accepts an optional third parameter for LIMIT
/*
$testUsers = Test::getMany(
'email LIKE :emailsnippet', [
':emailsnippet' => $emailSnippet
], 3); // LIMIT to THREE
*/
getById
$userId = 1;
$testUser = Test::getById($userId);
// element deduces the name of your primary key, it doesn't have to be 'id'
getAll
$testUsers = Test::getAll();
Update
Updating models is very similar to the methods we use at create
The only real difference is that we have to retrieve, rather than create the model.
Note:Some retrieval methods will get a single model, and some will get an array of models.
For the methods that retrieve a single model, you can work on it directly. getOne, getById
For the methods that retrieve many, you have to refer to them within the array. getMany, getAll
Update with getOne, getById
// getById
$user = Test::getById(1); // load
$user->name = "Fred"; // update
$user->save(); // save
// getOne
$user = Test::getOne(
'id = :id', [
':id' => 1
]
); // load
$user->name = "Fred"; // update
$user->save(); // save
Update with getMany, getAll
// getMany
$users = Test::getMany(
'email LIKE :emailsnippet', [
':emailsnippet' => 'davey%'
]);
$users[0]->name = "Fred";
$user[0]->save();
/*
// OR
foreach($users as $user) {
$user->name = "Fred";
$user->save();
}
*/
// getAll
// Same syntax apart from retrieval method
Delete
// getMany
$users = Test::getMany(
'email LIKE :emailsnippet', [
':emailsnippet' => 'davey%'
]);
$users[0]->name = "Fred";
$user[0]->save();
/*
// OR
foreach($users as $user) {
$user->name = "Fred";
$user->save();
}
*/
// getAll
// Same syntax apart from retrieval method
Delete
Currently there is only one delete model method, deleteById
$user = Test::getOne('email = :email', [
':email' => 'davie.jones@djlocker.com'
]); // retrieve in order to get id
Test::deleteById($user->id); // delete