If you take a look at the code you will find that it loads every JavaScript file via gzip.php, which is actually responsible for compressing the content.. So here is the code of gzip.php
Trang 1Whenever a form is submitted, we want to populate any model right after
initializing it Therefore, we have kept a configuration variable named auto_model_association for it If you set it to true, models will be automatically associated Here comes the library loader (core/main/library.php):
<?
class library{
private $loaded = array();
private function get($lib)
library.php helps only to load libraries via a Singleton
Now we will see the JavaScript loader, which by default delivers each library with gzip compression These days every browser supports gzip compression for faster loading of any object We are also distributing distributing our framework with built-in support for prototype, jQuery and script.aculo.us
Trang 3If you take a look at the code you will find that it loads every JavaScript file via gzip.php, which is actually responsible for compressing the content So here is the which is actually responsible for compressing the content So here is the code of gzip.php (core/js/gzip.php):
Lastly, we have another file, which helps us writing a unit test during the developing
of our application unittest.php is responsible for that and there is also a Boolean configuration flag for this: unit_test_enabled.
Here is core/main/unittest.php:
<?
class unittest
{
private static $results = array();
private static $testmode = false;
public static function setUp()
Trang 4if (true==$object) $result = "passed";
self::saveResult(true, $object, $result);
Trang 5$result = "<font color='red'><strong>failed</strong></font>"; else
$result = "<font color='green'><strong>passed</strong></font>"; $trace = self::getTrace();
$finalresult = "Test {$result} in Method:
if (!self::$testmode) return 0;
if (array_key_exists($key, $array))
{
$result = 1;
self::saveResult("Array has a key named '{$key}'",
"Array has a key named '{$key}'", $result); return ;
}
self::saveResult("Array has a key named '{$key}'",
"Array has not a key named '{$key}'", $result); }
public static function assertArrayNotHasKey($key, array $array, $message = '') {
}
self::saveResult("Array has not a key named '{$key}'",
"Array has a key named '{$key}'", $result); }
public static function assertContains($needle, $haystack,
$message = '')
{
Trang 6if (!self::$testmode) return 0;
if (in_array($needle,$haystack))
{
$result = 1;
self::saveResult("Array has a needle named '{$needle}'",
"Array has a needle named '{$needle}'", $result);
return ;
}
self::saveResult("Array has a needle named '{$needle}'",
"Array has not a needle named '{$needle}'", $result); }
}
?>
We must keep a built-in support for benchmarking our code to help profiling
Therefore, we have benchmark.php (core/main/benchmark.php) which performs it:
<?
class benchmark
{
private $times = array();
private $keys = array();
public function setMarker($key=null)
Trang 7Adding Database Support
Our framework must have a data abstraction layer to facilitate database operations painlessly We are going to provide support to three popular databases: SQLite, PostgreSQL, and MySQL Here is the code of our data abstraction layer in
private $state = "development";
public function construct()
$dbengine = new $driver($dbengineinfo[$this->state]);
Trang 10public function count()
Trang 11private function prepQuery($sql)
Trang 12public function transRollback()
elseif (FETCH_ROW == $fetchmode)
$row = sqlite_fetch_array($lastresult, SQLITE_NUM);
elseif (FETCH_OBJECT == $fetchmode)
Trang 13If you take a look at the code, you will find that we just implemented all the functions described in abstractdbdriver object in abstractdbdriver.php Here comes the driver file for MySQL, core/main/dbdrivers/mysqldriver.php:
else
$this->connection =
mysql_connect($dbinfo['dbhost'],$dbinfo['dbuser'], $dbinfo['dbpwd']);
mysql_select_db($dbinfo['dbname'],$this->connection);
}
else
throw new Exception("�ou must supply username, password,
hostname and database name for connecting to mysql"); }
public function execute($sql)
Trang 14}
$this->results[$hash] = mysql_query($sql,$this->connection); }
public function count()
// "DELETE FROM TABLE" returns 0 affected rows
// This hack modifies the query so that
// it returns the number of affected rows
Trang 15public function insertId()
Trang 16else
$this->connection = pg_connect("host={$dbinfo['dbname']}
port=5432 dbname={$dbinfo['dbname']} user={$dbinfo['$dbuser']}
Trang 17password={$dbinfo['dbpwd']}");
}
else
throw new Exception("�ou must supply username, password,
hostname and database name for connecting to postgresql");
Trang 18"DELETE FROM \\1 WHERE 1=1", $sql);
$table = func_num_args() > 0 ? func_get_arg(0) : null;
$column = func_num_args() > 1 ? func_get_arg(1) : null;
if ($table == null && $v >= '8.1')
Trang 19$sql = sprintf("SELECT CURRVAL('%s') as ins_id", $table); }
Trang 20Now our framework is done In the coming sections, we will see how to build
applications over this framework
Building Applications over our
Framework
Now is the colourful moment So far, we have done so many things to ease
developing applications over our framework So now in this section we will develop
a basic blog application and discuss how to take advantage of our framework For those unfamiliar with Blogs, they are simply web-based publishing systems, where people are allowed to write anything and publish it In this application we will allow users to write articles, display them, and also allow users to publish comments
Trang 21Let's create a MySQL database named packtblog with three tables; Users, Posts, and Comments Here is the database schema:
Table: Posts
+ -+ -+ -+ -+ -+ -+
| Field | Type | Null | Key | Default | Extra |
+ -+ -+ -+ -+ -+ -+
| id | int(11) | NO | PRI | NULL | auto_increment | | title | varchar(250) | �ES | | NULL | |
| content | text | �ES | | NULL | |
| user_id | int(11) | �ES | | NULL | |
| date | int(11) | �ES | | NULL | |
+ -+ -+ -+ -+ -+ -+
Table: Comments + -+ -+ -+ -+ -+ -+
| Field | Type | Null | Key | Default | Extra |
+ -+ -+ -+ -+ -+ -+
| id | int(11) | NO | PRI | NULL | auto_increment | | post_id | int(11) | �ES | | NULL | |
| content | text | �ES | | NULL | |
| date | int(11) | �ES | | NULL | |
| author | varchar(250) | �ES | | NULL | |
+ -+ -+ -+ -+ -+ -+
Table: Users + -+ -+ -+ -+ -+ -+
| Field | Type | Null | Key | Default | Extra |
+ -+ -+ -+ -+ -+ -+
| id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(100) | �ES | | NULL | |
| fullname | varchar(250) | �ES | | NULL | |
| email | varchar(250) | �ES | | NULL | |
| password | varchar(32) | �ES | | NULL | |
+ -+ -+ -+ -+ -+ -+
Authentication Controller
Let's design our main controller with users who, will be able to register, or log into, their system The code in the app/controllers/auth.php file is as follows:
<?
session_start();
class auth extends controller
Trang 23Here are the views for authentication controller:
<input type="password" name="password" /><br/>
<input type="submit" name="Submit" value="Login" />
Trang 24Fullname: <br/>
<input type="text" name="fullname" /><br/>
Email: <br/>
<input type="text" name="email" /><br/>
<input type="submit" name="submit" value="Register"/>
</form>
This will display the following screen:
Now comes the controller which will handle the blog operations
The code in the app/controllers/blog.php is as follows:
Trang 26And here are the views of our blog controller:
app/views/blog/display.php
<?
foreach ($posts as $post)
{
echo "<div id='post{$post['id']}' >";
echo "<b><a href='{$base_url}/blog/post/{$post['id']}'>
echo "<div id='post{$post['id']}' >";
echo "<b><a href='{$base_url}/blog/post/{$post['id']}'>
Trang 27This will display the following form:
And last but not the least here comes the config file Place it in
Trang 28In the rapid development of PHP applications, frameworks play a very important role That is why today there are so many enterprise-level frameworks in the market and you have so many choices We have learnt how to build a framework in this chapter which will also help to understand object loading, data abstraction layers, and the importance of separation Finally, we took a closer look at how applications are done
Trang 30Array to Object
about 52extending 52
class information functions
about 41class existence, checking 41class name, finding 43, 44currently loaded classes, finding 42methods existence, checking 42properties existence, checking 42type of class, checking 42
constructor 20-22 coupling 13
D
Data Abstraction Layers 178 Decorator pattern
about 84example 84, 86
design patterns
about 13, 63Abstract Factory 69
Trang 31PHP errors collecting, as exception 48, 49
M
MDB2
about 185database, connecting to 186, 187installing 185
prepared statements, executing 187, 188
memcached
about 61, 62installing 62
method chaining 59-61 methods 12
modifiers 18-20 MVC
about 205applications building, over framework
237, 238Authentication Controller 238-244bootstrap file, designing 206-224creating 206
database drivers 227-237database support, adding 224-226project, planning 206
MySQLi
about 165data selecting, in OO way 166, 167data updating, in OO way 167prepared statements 167
Trang 32constructors 20-22design patterns 63destructors 20-22getter, accessor methods 35history 6
inheritance 24interface 28-30modifiers 18-20object, coding 9, 10object, using 17, 18overloading class methods, magic methods for 37
polymorphism 27properties 32-34reflection API 93setter, accessor methods 35SPL objects 137
static method 32-34unit test 106
P
PDO
about 172DSN settings 174functions 177prepared statements, using with 175, 176stored procedures, calling 176
PHP
about 6ArrayObject 51Autoloading classes 59built in objects 137differences 11, 12exception handling 44-48history 5
iterators 49, 50
Trang 33Stored procedure, executing 171
Stored procedure executing, with PHP 172
structure 94, 95
ReflectionMethod
about 99methods 100methods, example 100-102structure 99, 100
ReflectionParameter
about 102example 103, 104structure 102
ReflectionProperty
about 104example 105, 106structure 104
S
SeekableIterator
about 155example 156
Serialization
about 54, 55magic methods 55, 58methods 55
SimpleXML API
about 192attributes, accessing 194CDATA Sections, managing 197documents, parsing 193DOM API 200
Flickr feeds, parsing 194-196XPath 198-200
Singleton pattern
about 75, 77purpose 75single instance feature, adding 76
SPL
objects 137
SPLFileInfo
about 159example 160, 161structure 159, 160
SPLFileObject
about 158
Trang 34Test Driven Development
preparing for 109starting 109-112Test Driven Development 120
X
XML
about 191advantages 191document structure 191, 192DOMDocument 191
SimpleXML API 192