With the basic structure for our Framework in place, it is time to start adding functionality to it. In this tutorial we will create a template manager and database handler, bringing us a step closer to a powerful Framework fit for use for almost any project. If you haven't already, be sure to review Part 1 of this series first!
MVC: Tweak the structure
In the first part of this tutorial, we created a folder called controllers to store the business logic for our applications. As daok pointed out in a comment, this isn't the best place for all of the business logic, and that a model should be used to store this logic. Previously, I have always used the database itself as the model in the majority of my applications, however, seperating this out a little more will make our framework even more powerful, and easier to extend.
So, what is MVC? MVC is a design pattern (as was the Singleton and Registry patterns we looked at in part 1), and it stands for Model View Controller, and the aim of this pattern is to seperate the business logic, user interface actions and the user interface from one another. Although we are not going to do anything with our models and controllers just yet, let's update our frameworks folder structure to include the "models" folder. The model will contain the main business logic, and the controller will deal with user interaction (e.g. submitting data, such as a comment). NB: Our __autoload function does not need to be changed.



Database Handler
Most websites and web applications which make use of PHP also make use of a database engine, such as MySQL. If we keep all of our database related functions in the same place, then we can (in theory) easily change the database engine we use. We can also make certain operations easier, such as inserting records, updating records or deleting records from the database. It can also make it easier when dealing with multiple database connections.
So...what should our database handler do:
- Manage connections to the database
- Try to provide some level of abstraction from the database
- Cache queries so we can use them later
- Make common database operations easier
Let's look at the code for our database handler, then we will discuss it afterwards.
1 |
<?php
|
2 |
|
3 |
/**
|
4 |
* Database management and access class
|
5 |
* This is a very basic level of abstraction
|
6 |
*/
|
7 |
class database { |
8 |
|
9 |
/**
|
10 |
* Allows multiple database connections
|
11 |
* probably not used very often by many applications, but still useful
|
12 |
*/
|
13 |
private $connections = array(); |
14 |
|
15 |
/**
|
16 |
* Tells the DB object which connection to use
|
17 |
* setActiveConnection($id) allows us to change this
|
18 |
*/
|
19 |
private $activeConnection = 0; |
20 |
|
21 |
/**
|
22 |
* Queries which have been executed and then "saved for later"
|
23 |
*/
|
24 |
private $queryCache = array(); |
25 |
|
26 |
/**
|
27 |
* Data which has been prepared and then "saved for later"
|
28 |
*/
|
29 |
private $dataCache = array(); |
30 |
|
31 |
/**
|
32 |
* Record of the last query
|
33 |
*/
|
34 |
private $last; |
35 |
|
36 |
|
37 |
/**
|
38 |
* Hello
|
39 |
*/
|
40 |
public function __construct() |
41 |
{
|
42 |
|
43 |
}
|
44 |
|
45 |
/**
|
46 |
* Create a new database connection
|
47 |
* @param String database hostname
|
48 |
* @param String database username
|
49 |
* @param String database password
|
50 |
* @param String database we are using
|
51 |
* @return int the id of the new connection
|
52 |
*/
|
53 |
public function newConnection( $host, $user, $password, $database ) |
54 |
{
|
55 |
$this->connections[] = new mysqli( $host, $user, $password, $database ); |
56 |
$connection_id = count( $this->connections )-1; |
57 |
if( mysqli_connect_errno() ) |
58 |
{
|
59 |
trigger_error('Error connecting to host. '.$this->connections[$connection_id]->error, E_USER_ERROR); |
60 |
}
|
61 |
|
62 |
return $connection_id; |
63 |
}
|
64 |
|
65 |
/**
|
66 |
* Close the active connection
|
67 |
* @return void
|
68 |
*/
|
69 |
public function closeConnection() |
70 |
{
|
71 |
$this->connections[$this->activeConnection]->close(); |
72 |
}
|
73 |
|
74 |
/**
|
75 |
* Change which database connection is actively used for the next operation
|
76 |
* @param int the new connection id
|
77 |
* @return void
|
78 |
*/
|
79 |
public function setActiveConnection( int $new ) |
80 |
{
|
81 |
$this->activeConnection = $new; |
82 |
}
|
83 |
|
84 |
/**
|
85 |
* Store a query in the query cache for processing later
|
86 |
* @param String the query string
|
87 |
* @return the pointed to the query in the cache
|
88 |
*/
|
89 |
public function cacheQuery( $queryStr ) |
90 |
{
|
91 |
if( !$result = $this->connections[$this->activeConnection]->query( $queryStr ) ) |
92 |
{
|
93 |
trigger_error('Error executing and caching query: '.$this->connections[$this->activeConnection]->error, E_USER_ERROR); |
94 |
return -1; |
95 |
}
|
96 |
else
|
97 |
{
|
98 |
$this->queryCache[] = $result; |
99 |
return count($this->queryCache)-1; |
100 |
}
|
101 |
}
|
102 |
|
103 |
/**
|
104 |
* Get the number of rows from the cache
|
105 |
* @param int the query cache pointer
|
106 |
* @return int the number of rows
|
107 |
*/
|
108 |
public function numRowsFromCache( $cache_id ) |
109 |
{
|
110 |
return $this->queryCache[$cache_id]->num_rows; |
111 |
}
|
112 |
|
113 |
/**
|
114 |
* Get the rows from a cached query
|
115 |
* @param int the query cache pointer
|
116 |
* @return array the row
|
117 |
*/
|
118 |
public function resultsFromCache( $cache_id ) |
119 |
{
|
120 |
return $this->queryCache[$cache_id]->fetch_array(MYSQLI_ASSOC); |
121 |
}
|
122 |
|
123 |
/**
|
124 |
* Store some data in a cache for later
|
125 |
* @param array the data
|
126 |
* @return int the pointed to the array in the data cache
|
127 |
*/
|
128 |
public function cacheData( $data ) |
129 |
{
|
130 |
$this->dataCache[] = $data; |
131 |
return count( $this->dataCache )-1; |
132 |
}
|
133 |
|
134 |
/**
|
135 |
* Get data from the data cache
|
136 |
* @param int data cache pointed
|
137 |
* @return array the data
|
138 |
*/
|
139 |
public function dataFromCache( $cache_id ) |
140 |
{
|
141 |
return $this->dataCache[$cache_id]; |
142 |
}
|
143 |
|
144 |
/**
|
145 |
* Delete records from the database
|
146 |
* @param String the table to remove rows from
|
147 |
* @param String the condition for which rows are to be removed
|
148 |
* @param int the number of rows to be removed
|
149 |
* @return void
|
150 |
*/
|
151 |
public function deleteRecords( $table, $condition, $limit ) |
152 |
{
|
153 |
$limit = ( $limit == '' ) ? '' : ' LIMIT ' . $limit; |
154 |
$delete = "DELETE FROM {$table} WHERE {$condition} {$limit}"; |
155 |
$this->executeQuery( $delete ); |
156 |
}
|
157 |
|
158 |
/**
|
159 |
* Update records in the database
|
160 |
* @param String the table
|
161 |
* @param array of changes field => value
|
162 |
* @param String the condition
|
163 |
* @return bool
|
164 |
*/
|
165 |
public function updateRecords( $table, $changes, $condition ) |
166 |
{
|
167 |
$update = "UPDATE " . $table . " SET "; |
168 |
foreach( $changes as $field => $value ) |
169 |
{
|
170 |
$update .= "`" . $field . "`='{$value}',"; |
171 |
}
|
172 |
|
173 |
// remove our trailing ,
|
174 |
$update = substr($update, 0, -1); |
175 |
if( $condition != '' ) |
176 |
{
|
177 |
$update .= "WHERE " . $condition; |
178 |
}
|
179 |
|
180 |
$this->executeQuery( $update ); |
181 |
|
182 |
return true; |
183 |
|
184 |
}
|
185 |
|
186 |
/**
|
187 |
* Insert records into the database
|
188 |
* @param String the database table
|
189 |
* @param array data to insert field => value
|
190 |
* @return bool
|
191 |
*/
|
192 |
public function insertRecords( $table, $data ) |
193 |
{
|
194 |
// setup some variables for fields and values
|
195 |
$fields = ""; |
196 |
$values = ""; |
197 |
|
198 |
// populate them
|
199 |
foreach ($data as $f => $v) |
200 |
{
|
201 |
|
202 |
$fields .= "`$f`,"; |
203 |
$values .= ( is_numeric( $v ) && ( intval( $v ) == $v ) ) ? $v."," : "'$v',"; |
204 |
|
205 |
}
|
206 |
|
207 |
// remove our trailing ,
|
208 |
$fields = substr($fields, 0, -1); |
209 |
// remove our trailing ,
|
210 |
$values = substr($values, 0, -1); |
211 |
|
212 |
$insert = "INSERT INTO $table ({$fields}) VALUES({$values})"; |
213 |
$this->executeQuery( $insert ); |
214 |
return true; |
215 |
}
|
216 |
|
217 |
/**
|
218 |
* Execute a query string
|
219 |
* @param String the query
|
220 |
* @return void
|
221 |
*/
|
222 |
public function executeQuery( $queryStr ) |
223 |
{
|
224 |
if( !$result = $this->connections[$this->activeConnection]->query( $queryStr ) ) |
225 |
{
|
226 |
trigger_error('Error executing query: '.$this->connections[$this->activeConnection]->error, E_USER_ERROR); |
227 |
}
|
228 |
else
|
229 |
{
|
230 |
$this->last = $result; |
231 |
}
|
232 |
|
233 |
}
|
234 |
|
235 |
/**
|
236 |
* Get the rows from the most recently executed query, excluding cached queries
|
237 |
* @return array
|
238 |
*/
|
239 |
public function getRows() |
240 |
{
|
241 |
return $this->last->fetch_array(MYSQLI_ASSOC); |
242 |
}
|
243 |
|
244 |
/**
|
245 |
* Gets the number of affected rows from the previous query
|
246 |
* @return int the number of affected rows
|
247 |
*/
|
248 |
public function affectedRows() |
249 |
{
|
250 |
return $this->$this->connections[$this->activeConnection]->affected_rows; |
251 |
}
|
252 |
|
253 |
/**
|
254 |
* Sanitize data
|
255 |
* @param String the data to be sanitized
|
256 |
* @return String the sanitized data
|
257 |
*/
|
258 |
public function sanitizeData( $data ) |
259 |
{
|
260 |
return $this->connections[$this->activeConnection]->real_escape_string( $data ); |
261 |
}
|
262 |
|
263 |
/**
|
264 |
* Deconstruct the object
|
265 |
* close all of the database connections
|
266 |
*/
|
267 |
public function __deconstruct() |
268 |
{
|
269 |
foreach( $this->connections as $connection ) |
270 |
{
|
271 |
$connection->close(); |
272 |
}
|
273 |
}
|
274 |
}
|
275 |
?>
|
Before discussing this in more detail, I should point out that this database handler is very basic. We could provide complete abstraction by not executing queries directly, but instead constructing queries based on paramaters to a query function, and then executing it.
Our delete, insert and update record methods make it easier to perform some common tasks (as I mentioned above we could extend this to do much much more), by only providing information such as the table name, an array of fields and coresponding values, limit values and conditions. Queries can also be "cached" so that we can do things with them later. I find this feature (as well as the ability to "cache" arrays of data) is very handy when combined with a template manager, as we can easily iterate through rows of data and populate it into our templates with little fuss, as you will see when we look at the template manager.
1 |
// insert record
|
2 |
$registry->getObject('db')->insertRecords( 'testTable', array('name'=>'Michael' ) ); |
3 |
// update a record
|
4 |
$registry->getObject('db')->updateRecords( 'testTable', array('name'=>'MichaelP' ), 'ID=2' ); |
5 |
// delete a record (well, upto 5 in this case)
|
6 |
$registry->getObject('db')->deleteRecords( 'testTable', "name='MichaelP'", 5 ); |
We can also work with multiple database connections relatively easily, so long as we switch between the appropriate connections when we need to (although this won't work when caching queries and retrieving them via our template manager without further work), for example, the code snippet below would allow us to delete records from two databases.
1 |
// our second database connection (let's assume we already have a connection to our main DB)
|
2 |
$newConnection = $registry->getObject('db')->newConnection('localhost', 'root', 'password', 'secondDB'); |
3 |
// delete from the primary db connection
|
4 |
$registry->getObject('db')->deleteRecords( 'testTable', "name='MichaelP'", 5 ); |
5 |
// change our active db connection, to allow future queries to be on the second connection
|
6 |
$registry->getObject('db')->setActiveConnection( $newConnection ); |
7 |
// delete from the secondary db connection
|
8 |
$registry->getObject('db')->deleteRecords( 'testTable', "name='MichaelP'", 5 ); |
9 |
// revert the active connection so future queries are on the primary db connection
|
10 |
$registry->getObject('db')->setActiveConnection( 0 ); |
How might we want to extend this class?
- Full abstraction
- Make use of inheritance, create an interface and have database classes inherit from it, each for different database engines
- Store the connection ID's along with the query when caching queries
- Improve data sanitizing, depending on the type of data we wish to sanitize
Template Manager
The template manager will handle all of the output, it needs to be able to work with various different template files, replace placeholders (I call them tags) with data and iterate through parts of the template with multiple rows of data from the database.
To make things easier, we will make use of a page class to contain the content related to the page, this also makes it easier for us to extend this and add features to it later. The template manager will manage this object.
1 |
<?php
|
2 |
|
3 |
// prevent this file being called directly
|
4 |
if ( ! defined( 'PCAFW' ) ) |
5 |
{
|
6 |
echo 'This file can only be called via the main index.php file, and not directly'; |
7 |
exit(); |
8 |
}
|
9 |
|
10 |
/**
|
11 |
* Template manager class
|
12 |
*/
|
13 |
class template { |
14 |
|
15 |
private $page; |
16 |
|
17 |
/**
|
18 |
* Hello!
|
19 |
*/
|
20 |
public function __construct() |
21 |
{
|
22 |
include( APP_PATH . '/PCARegistry/objects/page.class.php'); |
23 |
$this->page = new Page(); |
24 |
|
25 |
}
|
26 |
|
27 |
/**
|
28 |
* Add a template bit onto our page
|
29 |
* @param String $tag the tag where we insert the template e.g. {hello}
|
30 |
* @param String $bit the template bit (path to file, or just the filename)
|
31 |
* @return void
|
32 |
*/
|
33 |
public function addTemplateBit( $tag, $bit ) |
34 |
{
|
35 |
if( strpos( $bit, 'skins/' ) === false ) |
36 |
{
|
37 |
$bit = 'skins/' . PCARegistry::getSetting('skin') . '/templates/' . $bit; |
38 |
}
|
39 |
$this->page->addTemplateBit( $tag, $bit ); |
40 |
}
|
41 |
|
42 |
/**
|
43 |
* Put the template bits into our page content
|
44 |
* Updates the pages content
|
45 |
* @return void
|
46 |
*/
|
47 |
private function replaceBits() |
48 |
{
|
49 |
$bits = $this->page->getBits(); |
50 |
foreach( $bits as $tag => $template ) |
51 |
{
|
52 |
$templateContent = file_get_contents( $bit ); |
53 |
$newContent = str_replace( '{' . $tag . '}', $templateContent, $this->page->getContent() ); |
54 |
$this->page->setContent( $newContent ); |
55 |
}
|
56 |
}
|
57 |
|
58 |
/**
|
59 |
* Replace tags in our page with content
|
60 |
* @return void
|
61 |
*/
|
62 |
private function replaceTags() |
63 |
{
|
64 |
// get the tags
|
65 |
$tags = $this->page->getTags(); |
66 |
// go through them all
|
67 |
foreach( $tags as $tag => $data ) |
68 |
{
|
69 |
if( is_array( $data ) ) |
70 |
{
|
71 |
|
72 |
if( $data[0] == 'SQL' ) |
73 |
{
|
74 |
// it is a cached query...replace DB tags
|
75 |
$this->replaceDBTags( $tag, $data[1] ); |
76 |
}
|
77 |
elseif( $data[0] == 'DATA' ) |
78 |
{
|
79 |
// it is some cached data...replace data tags
|
80 |
$this->replaceDataTags( $tag, $data[1] ); |
81 |
}
|
82 |
}
|
83 |
else
|
84 |
{
|
85 |
// replace the content
|
86 |
$newContent = str_replace( '{' . $tag . '}', $data, $this->page->getContent() ); |
87 |
// update the pages content
|
88 |
$this->page->setContent( $newContent ); |
89 |
}
|
90 |
}
|
91 |
}
|
92 |
|
93 |
/**
|
94 |
* Replace content on the page with data from the DB
|
95 |
* @param String $tag the tag defining the area of content
|
96 |
* @param int $cacheId the queries ID in the query cache
|
97 |
* @return void
|
98 |
*/
|
99 |
private function replaceDBTags( $tag, $cacheId ) |
100 |
{
|
101 |
$block = ''; |
102 |
$blockOld = $this->page->getBlock( $tag ); |
103 |
|
104 |
// foreach record relating to the query...
|
105 |
while ($tags = PCARegistry::getObject('db')->resultsFromCache( $cacheId ) ) |
106 |
{
|
107 |
$blockNew = $blockOld; |
108 |
// create a new block of content with the results replaced into it
|
109 |
foreach ($tags as $ntag => $data) |
110 |
{
|
111 |
$blockNew = str_replace("{" . $ntag . "}", $data, $blockNew); |
112 |
}
|
113 |
$block .= $blockNew; |
114 |
}
|
115 |
$pageContent = $this->page->getContent(); |
116 |
// remove the seperator in the template, cleaner HTML
|
117 |
$newContent = str_replace( '<!-- START ' . $tag . ' -->' . $blockOld . '<!-- END ' . $tag . ' -->', $block, $pageContent ); |
118 |
// update the page content
|
119 |
$this->page->setContent( $newContent ); |
120 |
}
|
121 |
|
122 |
/**
|
123 |
* Replace content on the page with data from the cache
|
124 |
* @param String $tag the tag defining the area of content
|
125 |
* @param int $cacheId the datas ID in the data cache
|
126 |
* @return void
|
127 |
*/
|
128 |
private function replaceDataTags( $tag, $cacheId ) |
129 |
{
|
130 |
$block = $this->page->getBlock( $tag ); |
131 |
$blockOld = $block; |
132 |
while ($tags = PCARegistry::getObject('db')->dataFromCache( $cacheId ) ) |
133 |
{
|
134 |
foreach ($tags as $tag => $data) |
135 |
{
|
136 |
$blockNew = $blockOld; |
137 |
$blockNew = str_replace("{" . $tag . "}", $data, $blockNew); |
138 |
}
|
139 |
$block .= $blockNew; |
140 |
}
|
141 |
$pageContent = $this->page->getContent(); |
142 |
$newContent = str_replace( $blockOld, $block, $pageContent ); |
143 |
$this->page->setContent( $newContent ); |
144 |
}
|
145 |
|
146 |
/**
|
147 |
* Get the page object
|
148 |
* @return Object
|
149 |
*/
|
150 |
public function getPage() |
151 |
{
|
152 |
return $this->page; |
153 |
}
|
154 |
|
155 |
/**
|
156 |
* Set the content of the page based on a number of templates
|
157 |
* pass template file locations as individual arguments
|
158 |
* @return void
|
159 |
*/
|
160 |
public function buildFromTemplates() |
161 |
{
|
162 |
$bits = func_get_args(); |
163 |
$content = ""; |
164 |
foreach( $bits as $bit ) |
165 |
{
|
166 |
|
167 |
if( strpos( $bit, 'skins/' ) === false ) |
168 |
{
|
169 |
$bit = 'skins/' . PCARegistry::getSetting('skin') . '/templates/' . $bit; |
170 |
}
|
171 |
if( file_exists( $bit ) == true ) |
172 |
{
|
173 |
$content .= file_get_contents( $bit ); |
174 |
}
|
175 |
|
176 |
}
|
177 |
$this->page->setContent( $content ); |
178 |
}
|
179 |
|
180 |
/**
|
181 |
* Convert an array of data (i.e. a db row?) to some tags
|
182 |
* @param array the data
|
183 |
* @param string a prefix which is added to field name to create the tag name
|
184 |
* @return void
|
185 |
*/
|
186 |
public function dataToTags( $data, $prefix ) |
187 |
{
|
188 |
foreach( $data as $key => $content ) |
189 |
{
|
190 |
$this->page->addTag( $key.$prefix, $content); |
191 |
}
|
192 |
}
|
193 |
|
194 |
public function parseTitle() |
195 |
{
|
196 |
$newContent = str_replace('<title>', '<title>'. $page->getTitle(), $this->page->getContent() ); |
197 |
$this->page->setContent( $newContent ); |
198 |
}
|
199 |
|
200 |
/**
|
201 |
* Parse the page object into some output
|
202 |
* @return void
|
203 |
*/
|
204 |
public function parseOutput() |
205 |
{
|
206 |
$this->replaceBits(); |
207 |
$this->replaceTags(); |
208 |
$this->parseTitle(); |
209 |
}
|
210 |
|
211 |
|
212 |
|
213 |
}
|
214 |
?>
|
So, what exactly does this class do?
Creates our page object, and bases it from template files, the page object contains the content and information which is needed to make-up the HTML of the page. We then buildFromTemplate('templatefile.tpl.php', 'templatefile2.tpl.php') to get the initial content for our page, this method takes any number of template files as its arguments, and stitches them together in order, useful for header, content and footer templates.
Manages the content associated with the page by helping the page object maintain a record of data to be replaced into the page, and also additional template bits which need to be incorporated into the page (addTemplateBit('userbar','usertoolsbar.tpl.php')).
Adds data and content to the page by performing various replace operations on the page content, including retrieving results from a cached query and adding them to the page.
The template file needs to mark within itself where a cached query needs to be retrieved and the data from the query replaced. When the template manager encounters a tag to replace which is a query, it gets the chunk of the page where it needs to iterate through by calling getBlock('block') on the page object. This chunk of content is then copied for each record in the query, and has tags within it replaced with the results from the query. We will take a look at how this looks in the template later in this tutorial.
Template Manager: Page
The page object is managed by the template manager, and it used to contain all of the details related to the page. This leaves the template manager free to manage, while making it easier for us to extend the functionality of this at a later date.
1 |
<?php
|
2 |
|
3 |
/**
|
4 |
* This is our page object
|
5 |
* It is a seperate object to allow some interesting extra functionality to be added
|
6 |
* Some ideas: passwording pages, adding page specific css/js files, etc
|
7 |
*/
|
8 |
class page { |
9 |
|
10 |
// room to grow later?
|
11 |
private $css = array(); |
12 |
private $js = array(); |
13 |
private $bodyTag = ''; |
14 |
private $bodyTagInsert = ''; |
15 |
|
16 |
// future functionality?
|
17 |
private $authorised = true; |
18 |
private $password = ''; |
19 |
|
20 |
// page elements
|
21 |
private $title = ''; |
22 |
private $tags = array(); |
23 |
private $postParseTags = array(); |
24 |
private $bits = array(); |
25 |
private $content = ""; |
26 |
|
27 |
/**
|
28 |
* Constructor...
|
29 |
*/
|
30 |
function __construct() { } |
31 |
|
32 |
public function getTitle() |
33 |
{
|
34 |
return $this->title; |
35 |
}
|
36 |
|
37 |
public function setPassword( $password ) |
38 |
{
|
39 |
$this->password = $password; |
40 |
}
|
41 |
|
42 |
public function setTitle( $title ) |
43 |
{
|
44 |
$this->title = $title; |
45 |
}
|
46 |
|
47 |
public function setContent( $content ) |
48 |
{
|
49 |
$this->content = $content; |
50 |
}
|
51 |
|
52 |
public function addTag( $key, $data ) |
53 |
{
|
54 |
$this->tags[$key] = $data; |
55 |
}
|
56 |
|
57 |
public function getTags() |
58 |
{
|
59 |
return $this->tags; |
60 |
}
|
61 |
|
62 |
public function addPPTag( $key, $data ) |
63 |
{
|
64 |
$this->postParseTags[$key] = $data; |
65 |
}
|
66 |
|
67 |
/**
|
68 |
* Get tags to be parsed after the first batch have been parsed
|
69 |
* @return array
|
70 |
*/
|
71 |
public function getPPTags() |
72 |
{
|
73 |
return $this->postParseTags; |
74 |
}
|
75 |
|
76 |
/**
|
77 |
* Add a template bit to the page, doesnt actually add the content just yet
|
78 |
* @param String the tag where the template is added
|
79 |
* @param String the template file name
|
80 |
* @return void
|
81 |
*/
|
82 |
public function addTemplateBit( $tag, $bit ) |
83 |
{
|
84 |
$this->bits[ $tag ] = $bit; |
85 |
}
|
86 |
|
87 |
/**
|
88 |
* Get the template bits to be entered into the page
|
89 |
* @return array the array of template tags and template file names
|
90 |
*/
|
91 |
public function getBits() |
92 |
{
|
93 |
return $this->bits; |
94 |
}
|
95 |
|
96 |
/**
|
97 |
* Gets a chunk of page content
|
98 |
* @param String the tag wrapping the block ( <!-- START tag --> block <!-- END tag --> )
|
99 |
* @return String the block of content
|
100 |
*/
|
101 |
public function getBlock( $tag ) |
102 |
{
|
103 |
preg_match ('#<!-- START '. $tag . ' -->(.+?)<!-- END '. $tag . ' -->#si', $this->content, $tor); |
104 |
|
105 |
$tor = str_replace ('<!-- START '. $tag . ' -->', "", $tor[0]); |
106 |
$tor = str_replace ('<!-- END ' . $tag . ' -->', "", $tor); |
107 |
|
108 |
return $tor; |
109 |
}
|
110 |
|
111 |
public function getContent() |
112 |
{
|
113 |
return $this->content; |
114 |
}
|
115 |
|
116 |
}
|
117 |
?>
|
How can this class be extended and improved?
- PostParseTags: You may wish to have tags replaced after most of the page has been parsed, maybe content in the database contains tags which need to be parsed.
- Passworded pages: Assign a password to a page, check to see if the user has the password in a cookie or a session to allow them to see the page.
- Restricted pages (although we need our authentication components first!)
- Altering the
- Dynamically adding references to javascript and css files based on the page or application.
Load core objects
Now that we have some objects which our registry is going to store for us, we need to tell the registry which objects these are. I've created a method in the PCARegistry object called loadCoreObjects which (as it says) loads the core objects. This means can can just call this from our index.php file to load the registry with these objects.
1 |
public function storeCoreObjects() |
2 |
{
|
3 |
$this->storeObject('database', 'db' ); |
4 |
$this->storeObject('template', 'template' ); |
5 |
}
|
This method can be altered later to encorporate the other core objects the registry should load, of course there may be objects which we want our registry to manage, but only depending on the application the framework is used for. These objects would be loaded outside of this method.
Some Data
So that we can demonstrate the new features added to our framework, we need a database to make use of the database handler, and some of the template management functions (where we replace a block of content with the rows in the database).
The demonstration site we will make with our framework by the end of this series of tutorials is a website with a members directory, so let's make a very basic database table for members profiles, containing an ID, name, and email address.



Obviously, we need a few rows of data in this table!
A quick template
In order for anything to be displayed, we need a basic template, where we will list the data from our members table.
1 |
<html>
|
2 |
<head>
|
3 |
<title> Powered by PCA Framework</title> |
4 |
</head>
|
5 |
<body>
|
6 |
<h1>Our Members</h1> |
7 |
<p>Below is a list of our members:</p> |
8 |
<ul>
|
9 |
<!-- START members -->
|
10 |
<li>{name} {email}</li> |
11 |
<!-- END members -->
|
12 |
</ul>
|
13 |
</body>
|
14 |
</html>
|
The START members and END members HTML comments denote the members block (which is obtained via the getBlock() method on the page), this is where the template manager will iterate through the records in the database and display them.
Framework in use
Now, we need to bring this all together, with our index.php file:
1 |
// require our registry
|
2 |
require_once('PCARegistry/pcaregistry.class.php'); |
3 |
$registry = PCARegistry::singleton(); |
4 |
|
5 |
// store those core objects
|
6 |
$registry->storeCoreObjects(); |
7 |
|
8 |
// create a database connection
|
9 |
$registry->getObject('db')->newConnection('localhost', 'root', '', 'pcaframework'); |
10 |
|
11 |
// set the default skin setting (we will store these in the database later...)
|
12 |
$registry->storeSetting('default', 'skin'); |
13 |
|
14 |
// populate our page object from a template file
|
15 |
$registry->getObject('template')->buildFromTemplates('main.tpl.php'); |
16 |
|
17 |
// cache a query of our members table
|
18 |
$cache = $registry->getObject('db')->cacheQuery('SELECT * FROM members'); |
19 |
|
20 |
// assign this to the members tag
|
21 |
$registry->getObject('template')->getPage()->addTag('members', array('SQL', $cache) ); |
22 |
|
23 |
// set the page title
|
24 |
$registry->getObject('template')->getPage()->setTitle('Our members'); |
25 |
|
26 |
// parse it all, and spit it out
|
27 |
$registry->getObject('template')->parseOutput(); |
28 |
print $registry->getObject('template')->getPage()->getContent(); |
If we now view this page in our web browser, the results of the query are displayed on the page:

Coming in part 3...
In part three we will take a slight detour from the development side of our Framework, and look at how to design with our framework in mind, and how to slice up HTML templates so that they are suitable for our framework. When we start to build our first application with our framework, we will look in more detail at some of the workings of these classes. Finally, thank you for your comments last time!
- Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.