I recently needed a simple model type object with CRUD operations and persistence to demonstrate some new PHP controller and routing software. Setting up the persistence layer in a database seemed to involve a lot of overhead, assuming that anyone wanting to run the demo has the time and privileges involved. It is also a shared repository of data - the demo will allow people to create, update and delete whatever they like - which may cause some issues.
Instead of using a database for the persistence I instead decided to store the data in a session variable. This mitigates any setup required and allows users to add and edit the data in their own personal sandbox. SessionRecord is a simple wrapper around storing data in the user’s session, it provides familiar methods for CRUD operations on your models.
It requires PHP 5.3 as it makes use of late static binding and a few lambdas here and there. It provides …
The code is on Github at http://github.com/testomatic/examples/tree/master/php/SessionRecord/
<?php
require 'SessionRecord.php';
/**
* Create a Book model type, $_namespace is used to store data in the session,
* think of it as an SQL table name :)
*/
class Book extends SessionRecord
{
protected static $_namespace = 'books';
}
/**
* You can init some data, this will happen the first time
* the $_SESSION object is created
*/
Book::init(
array(
array(
'title' => 'Cider with Rosie',
'author' => 'Laurie Lee',
'id' => 1,
),
array(
'title' => 'Lord of the Flies',
'author' => 'William Golding',
'id' => 2,
)
)
);
/**
* We then have some of the usual finder type functionality
*/
$books = Book::findAll(); // array() of objects
$books = Book::findAllBy('author', 'Laurie Lee'); // array() of objects by Laurie Lee
$book = Book::findFirstBy('id', '1'); // object with id 1 or false
/**
* You can create a new Book which gets stored to $_SESSION and assigned an ID
*/
$book = Book::create(array('title' => 'A Moment of War', 'author' => 'Laurie Lee'));
$book->id // 3
/**
* You can modify and save a Book
*/
$book->title = 'As I Walked Out One Midsummer Morning';
$book->save();
/**
* Or delete it from the storage
*/
$book->delete();
/**
* And if you want to clear all the data in $_SESSION
*/
Book::reset();
?>
Comment
blog comments powered by Disqus