admit frankly that I came to the Zend Framework with practices at IBM, where he came to me to test a hybrid data engine (pureXML in DB2 9). I decided to play because the server Zend Core for IBM (fairly quickly switched to Zend Core 2) and at his installation ZF noticed.
In the era of object-oriented programming we have a wide range of APIs, which we record zdeserializują array to an object class, allow it to easily modify and re-serialization. A prime example is at the moment probably the Java Persistence API is described in detail by Jacek Laskowski , but of course such a possibility in the Zend Framework could not miss.
therefore decided to discuss the mechanism and draw attention to an important issue in my view - to avoid deserialization of objects and use arrays or associative arrays there (in Java it would use a collection or array built-in types), where it is important to efficient processing of information.
In my example I will use the table that describes a bunch of cosmic rays, similar to the one I work every day:
CREATE TABLE cosmic_rays (
id serial NOT NULL, - Automatically generated identifier
nix_date float8, - Unix ' The new timestamp
peak_particles float 8, - The number of registered particles
az float4, - The source of the coordinates of the horizontal - the azimuth
float4, - The source of horizontal coordinates - the distance from the zenith
ra float4, - The source of the coordinates of the blue - dec rekt Mother Ascensión
float4, - The source of the coordinates of the blue - declination
l float4, - The sources in the galactic coordinates - the width of gal
b float4, - The sources in the galactic coordinates - the length of gal
CONSTRAINT id PRIMARY KEY (id)
) WITHOUT Oids;
As you might guess the table is prepared for the base based on PostgreSQL, but do not need multiple treatments in order to adapt it to another database system.
in the project directory structure
As in the previous example based on Zend Framework structure will look as follows:
- application
- controllers
- IndexController.php
- models
- CosmicRays.php
- views
- controllers
- configuration
- config.xml
- library
- Zend
- Zend.php
- public
- . Htaccess index.php
File . htaccess file also contains only control information for the rewrite module:
RewriteEngine on RewriteRule .* index.php
Initializing database connection
config.xml file will contain the necessary to compile a database connection information:
\u0026lt;? xml version = "1.0" encoding = "utf-8">
\u0026lt;configData>
\u0026lt;db>
\u0026lt;adapter> PDO_Pgsql \u0026lt;/ adapter>
\u0026lt;configuration>
\u0026lt;host> localhost \u0026lt;/ host>
\u0026lt;port> 5432 \u0026lt;/ port>
\u0026lt;dbname> Database \u0026lt;/ dbname>
\u0026lt;username> user \u0026lt;/ username>
\u0026lt;password> *****\u0026lt;/ password>
\u0026lt;/ configuration>
\u0026lt;/ db>
\u0026lt;/ configData>
We can then proceed to configure the bootstrap index.php file:
/ / Set the path
set_include_path ('..' PATH_SEPARATOR
. '. / library'. PATH_SEPARATOR
. '. / application / models /'. PATH_SEPARATOR
. get_include_path ());
/ / Load the class require_once Zend_Loader
'Zend / Loader.php';
try {/ / Load the necessary classes
Zend_Loader:: loadClass ('Zend_Config_Xml');
Zend_Loader:: loadClass ('Zend_Db');
Zend_Loader:: loadClass ('Zend_Db_Table');
Zend_Loader:: loadClass ('Zend_Registry');
Zend_Loader:: loadClass ('Zend_View');
Zend_Loader:: loadClass ('Zend_Controller_Front');
/ / We set the base address
$ baseurl = substr ($ _SERVER ['PHP_SELF'], 0 ,
strpos ($ _SERVER ['PHP_SELF'], '/ index.php'));
/ / Load the configuration database file XML (db branch)
$ config = new Zend_Config_Xml ('. / Configuration / config.xml', 'db');
/ / Create a connection to the database and making it the default for models
tables $ db = Zend_Db: factory ($ config-> adapter,
$ config-> configuration-> asArray ());
Zend_Db_Table:: setDefaultAdapter ($ db);
/ / Configure class
view $ view = new Zend_View ();
$ view-> baseurl = $ baseurl;
$ view-> setScriptPath ('. / application / views');
/ / Place it in the registry
Zend_Registry:: set ('view', $ view);
/ / Initialize the main controller
$ FrontController = Zend_Controller_Front:: getInstance ();
$ FrontController-> setRouter ($ router);
$ FrontController-> setBaseUrl ($ baseurl);
$ FrontController-> setControllerDirectory (
'. / application / controllers');
$ FrontController-> throwExceptions (true);
$ FrontController-> returnResponse (true);
/ / Initialize the response object $ response
= $ FrontController-> dispatch ();
$ response-> renderExceptions (true);
$ response-> setHeader ('Pragma', 'no-cache');
$ response-> setHeader ('Cache-Control', 'no-cache');
/ / Display the
echo $ response;
} catch (Exception $ e) {
/ / Exception handling
die ($ e-> getMessage ());}
As can be seen adding support to our data base required us to 6 lines of code (including the import of the relevant files libraries). It
Zend_Config_Xml (inheriting Zend_Config) is an object that allows for easy loading of configuration files in the form of XML documents. Its use is very similar to handling XML files using SimpleXML (see earlier post).
Initialization make calls through a static factory method Zend_Db class, where we serve the type of adapter (for most databases are PDO adapters, adapters have only their own DB2, Oracle, and MySQLi), and configuration parameters.
The static method of class setDefaultAdapter Zend_Db_Table set to link to all the objects associated with tables.
Our first model
CosmicRays.php In the file put, our model for the table cosmic_rays:
Zend_Loader:: loadClass ('Zend_Db_Table');
CosmicRays class extends Zend_Db_Table {
_setup protected function () {
/ / standard ZF set the table name as a string representing
/ / _ after the last character in the name of the class model, so we change it
$ this-> _name = 'cosmic_rays';
/ / We can also set your primary key (if other than d)
/ / and the schema of the table (especially important for databases such as DB2 or Oracle)
/ / On Finally we load the base class setting
parent:: _setup ();}
}
And it would be enough. We just have to create an object of class CosmicRays and we can modify the objects. There we have the method (I mentioned the most important):
- fetchNew () - creates a new empty "record"
- fetchRow ($ where, $ order) - returns the first "record" with the result satisfies the condition $ where $ order of the rearrangement
- fetchAll ($ where, $ order) - returns all the "records"
- insert ($ data) - inserts a "record" on the basis of an associative array
- update ($ data, $ Where) - updates the data based on an associative array
worth noting that the method returns the object fetchAll Zend_Db_Table_Rowset type of iterator for objects Zend_Db_Table_Rows (so you can browse the collection using a foreach loop). FetchNew fetchRow methods and return to us an object of type Zend_Db_Table_Row. Each object
Zend_Db_Table_Row available to us in a manner similar to the objects stClass. Therefore, we can modify them easily (it is not acceptable merely modified primary key), for example
$ mp = new CosmicRays ();
$ row = $ cr-> fetchRow ('id = 10 ");
$ row-> ra = 0;
$ row-> update ();
quoted above, the method update () gives us the opportunity to update the object. You can also save () method allows you to record a new object created using the method fetchNew ().
performance problem
problem for which I found was to download only two columns from the entire table. Of course, we can create an object select. However, this requires the placement of the object $ db in the registry, or wyłuskania from the object model.
course for queries joining data from multiple table is practically the only method. But what if we want the shell with only one table? Let
new method in the model class:
public function fetchAllColumns ( $ columns = null , $ where = null, $ order = null, $
count = null, $ offset = null) {
/ / selection
tool $ select = $ this-> _db-> select ();
/ / Set columns
$ columns = (is_null ($ columns))? $ this-> _cols: $ columns;
/ / the FROM clause $ select
-> from ($ this-> _name, $columns);
// the WHERE clause
$where = (array) $where;
foreach ($where as $key => $val) {
// is $key an int?
if (is_int($key)) {
// $val is the full condition
$select->where($val);
} else {
// $key is the condition with placeholder,
// and $val is quoted into the condition
$select->where($key, $val);
}
}
// the ORDER clause
if (!is_array($order)) {
$order = array ($ order);}
foreach ($ order as $ val) {$
select-> order ($ val);}
/ / the LIMIT clause $ select
-> limit ($ count, $ offset );
/ / return the results $ stmt
= $ this-> _db-> query ($ select);
$ data = $ stmt-> fetchAll (Zend_Db: FETCH_ASSOC);
return $ data;}
Those who watched the class Zend_Db_Table_Abstract quickly notice that my method is not nothing but a slightly modified method _fetch (...).
is worth a look at the implementations fetchAll (...) method of this class. Well, an associative array, it wraps in a Zend_Db_Table_Rowset. In situations where we want efficiency and low demand for memory should refrain from facilitating the class entails Zend_Db_Table_Rowset.
At the end of yet another council. Feel free to use the user unset ($ data), especially if the object $ data array is large in size, which still does not intend to use. Especially because the server administrators often do not provide for the php scripts more than 16MB of memory.
0 comments:
Post a Comment