diff options
author | wei <> | 2007-03-21 03:27:12 +0000 |
---|---|---|
committer | wei <> | 2007-03-21 03:27:12 +0000 |
commit | 5885bd12735637430e093c896499c3f26832fceb (patch) | |
tree | 53387f902c060685b5f466b042aa234baa301da6 | |
parent | 4b41982314af49396ee577c8d4dea0624b8e9096 (diff) |
minor AR updates, remove obsolete TApplication::$_pageService
-rw-r--r-- | HISTORY | 2 | ||||
-rw-r--r-- | demos/quickstart/protected/pages/Database/Scaffold.page | 80 | ||||
-rw-r--r-- | framework/Data/ActiveRecord/Scaffold/TScaffoldEditView.php | 4 | ||||
-rw-r--r-- | framework/Data/ActiveRecord/TActiveRecord.php | 1092 | ||||
-rw-r--r-- | framework/Data/ActiveRecord/TActiveRecordManager.php | 14 | ||||
-rw-r--r-- | framework/TApplication.php | 4 |
6 files changed, 626 insertions, 570 deletions
@@ -7,6 +7,7 @@ BUG: Ticket#549 - set/get Timestamp on TDatePicker shound handle "null" values ( BUG: Ticket#550 - explicitly include TCallbackClientSide in TCallbackOptions (Qiang) BUG: Ticket#553 - I18N quickstart sample does not work (Qiang) BUG: Ticket#555 - TNumberFormat throws exception (Qiang) +BUG: Ticket#573 - NumberFormat Bug (Wei) BUG: TXmlElement did not encode attribute and text values when being saved as a string (Qiang) BUG: SelectedIndices not return expected result for ActiveListBox (Wei) ENH: Ticket#503 - Localization and parameter tags can now appear as a substring in a property initial value (Qiang) @@ -53,6 +54,7 @@ BUG: Ticket#481 - Unable to cancel navigation when handling OnSideBarButtonClick BUG: Ticket#505 - cultureInfo::getEnglishName does not return an arrary (Wei) BUG: Ticket#508 - CultureInfo class: PHP Notice because of missing static declaration (Wei) BUG: Ticket#558 - TRadionButtonList generates a empty onclick attribute (Qiang) +BUG: Ticket#573 - NumberFormat Bug (Wei) BUG: typo in THttpResponse.writeFile() about sending headers (Qiang) Version 3.0.6 December 4, 2006 diff --git a/demos/quickstart/protected/pages/Database/Scaffold.page b/demos/quickstart/protected/pages/Database/Scaffold.page index 055cac26..b2d52b6d 100644 --- a/demos/quickstart/protected/pages/Database/Scaffold.page +++ b/demos/quickstart/protected/pages/Database/Scaffold.page @@ -17,6 +17,7 @@ the following builtin functionality: <ul>
<li>Listing of all active record items.</li>
+ <li>Searching records.</li>
<li>Paging and sorting.</li>
<li>Deleting an item.</li>
<li>Inserting a new item.</li>
@@ -39,7 +40,7 @@ table as defined in the <a href="?page=Database.ActiveRecord">Active Record</a> <com:TTextHighlighter Language="php" CssClass="source">
class UserRecord extends TActiveRecord
{
- const TABLE='users';
+ const TABLE='users';
public $username;
public $email;
@@ -51,9 +52,9 @@ class UserRecord extends TActiveRecord This <a href="?page=Fundamentals.Components#704">namespace</a> can be "imported" in the
<a href="?page=Configurations.AppConfig">Application Configuration</a>
using the <tt>application.xml</tt> file or through the php code using the <tt>Prado::using()</tt>
-method. The simplest way to provide CRUD functional is to use the
+method. To start using the
<com:DocLink ClassPath="System.Data.ActiveRecord.Scaffold.TScaffoldView" Text="TScaffoldView"/>
-where the <tt>RecordClass</tt> property value equals to an Active Record
+simply set the <tt>RecordClass</tt> property value equal to an Active Record
class name.
</p>
@@ -61,27 +62,83 @@ class name. <com:TScaffoldView RecordClass="UserRecord" />
</com:TTextHighlighter>
-<h2>Todo...</h2>
+<p>The above code will list the current records in the <tt>users</tt> table.
+Each record can be edited by clicking on the "edit" button and deleted by
+clicking on the "delete" button. A new record can be added by clicking on the
+"Add new record" button, enter some data (notice the automatic validation of required fields and data types), and click the "save" button.
+Specifying search terms in the search textbox to find particular records. Finally, the
+record list can be sorted for each column by changing the sorting column and order.
+</p>
+
+<p>The <tt>TScaffoldView</tt> is a template control composed of other scaffold controls.
+The following properties gives access to these composite controls.</p>
+<ul>
+ <li><b><tt>ListView</tt></b> -- the <tt>TScaffoldListView</tt> displaying the record list. </li>
+ <li><b><tt>EditView</tt></b> -- the <tt>TScaffoldEditView</tt> that renders the inputs for editing and adding records.</li>
+ <li><b><tt>SearchControl</tt></b> -- the <tt>TScaffoldSearch</tt> responsible to the search user interface.</li>
+</ul>
+<p>
+ All these composite controls can be customized as we shall see below.
+</p>
+
+<h2>TScaffoldListView</h2>
+
+<p>A list of Active Records can be displayed using the <tt>TScaffoldListView</tt>
+with the following useful properties.</p>
+<ul>
+ <li><b><tt>Header</tt></b> -- a <a href="?page=Controls.Repeater">TRepeater</a>
+displaying the Active Record property/field names. </li>
+ <li><b><tt>Sort</tt></b> -- a <a href="?page=Controls.List">TDropDownList</a> displaying the combination
+of properties and its possible ordering. </li>
+ <li><b><tt>Pager</tt></b> -- a <a href="?page=Controls.Pager">TPager</a> control displaying
+the links and/or buttons that navigate to different pages in the Active Record data.</li>
+ <li><b><tt>List</tt></b> -- a <a href="?page=Controls.Repeater">TRepeater</a> that renders a row of Active Record data.</li>
+</ul>
-<p>Other views... list view</p>
+<p>Custom rendering of the each Active Record can be achieved by specifying
+the <tt>ItemTemplate</tt> and/or <tt>AlternatingItemTemplate</tt> property of the <tt>List</tt>
+repeater.
+The <tt>TScaffoldListView</tt> will listen for two command events named "delete" and
+"edit". A "delete" command will delete a the record for the row where the "delete" command originates.
+An "edit" command will push the record data to be edited by a
+<tt>TScaffoldEditView</tt> with ID specified by the <tt>EditViewID</tt> property.
+The following example lists the usernames only with bold formatting.
+</p>
<com:TTextHighlighter Language="prado" CssClass="source">
-<com:TScaffoldListView RecordClass="UserRecord" />
+<com:TScaffoldListView RecordClass="UserRecord" >
+ <prop:List.ItemTemplate>
+ <strong><%# $this->Data->username %></strong>
+ </prop:List.ItemTemplate>
+</com:TScaffoldListView>
</com:TTextHighlighter>
-<p>edit view...</p>
+<div class="info"><b class="note">Info:</b>
+For the <tt>TScaffoldView</tt> the list view can be accessed throught the <tt>ListView</tt> property of a <tt>TScaffoldView</tt>.
+Thus, the subproperty <tt>ListView.List.ItemTemplate</tt> on <tt>TScaffoldView</tt>
+is equivalent to the <tt>List.ItemTemplate</tt> subproperty of <tt>TScaffoldListView</tt> in the above example.
+</div>
+
+<p>The <tt>SearchCondition</tt> property and
+<tt>SearchParameters</tt> property (takes array values) can be
+specified to customize the records to be shown. The <tt>SearchCondition</tt>
+will be used as the <tt>Condition</tt> property of <tt>TActiveRecordCriteria</tt>
+and the <tt>SearchParameters</tt> property corresponds to
+<tt>Parameters</tt> property of <tt>TActiveRecordCriteria</tt>.</p>
+
+<h2>TScaffoldEditView</h2>
<com:TTextHighlighter Language="prado" CssClass="source">
<com:TScaffoldEditView RecordPk="user1" RecordClass="UserRecord" />
</com:TTextHighlighter>
-<p>Combining list + edit views</p>
+<h2>Combining list + edit views</h2>
<com:TTextHighlighter Language="prado" CssClass="source">
<com:TScaffoldEditView ID="edit_view" RecordClass="UserRecord" />
<com:TScaffoldListView EditViewID="edit_view" RecordClass="UserRecord" />
</com:TTextHighlighter>
-<p>custom list view...</p>
+<h2>Customizing the TScaffoldView</h2>
<com:TTextHighlighter Language="prado" CssClass="source">
<com:TScaffoldView RecordClass="UserRecord" >
<prop:ListView.List.ItemTemplate>
@@ -90,10 +147,5 @@ class name. </prop:ListView.List.ItemTemplate>
</com:TScaffoldView/>
</com:TTextHighlighter>
-<p>To be completed...</p>
-
-<p>Address book example...</p>
-
-<com:RunBar PagePath="Database.Samples.Scaffold.Home" />
<div class="last-modified">$Id$</div></com:TContent>
\ No newline at end of file diff --git a/framework/Data/ActiveRecord/Scaffold/TScaffoldEditView.php b/framework/Data/ActiveRecord/Scaffold/TScaffoldEditView.php index 14b4098a..efc356f5 100644 --- a/framework/Data/ActiveRecord/Scaffold/TScaffoldEditView.php +++ b/framework/Data/ActiveRecord/Scaffold/TScaffoldEditView.php @@ -22,7 +22,9 @@ Prado::using('System.Data.ActiveRecord.Scaffold.TScaffoldBase'); * value (may be an array for composite keys).
*
* The default editor input controls are created based on the column types.
- * The editor layout can be specified by a renderer. A renderer is an external
+ * The editor layout can be specified by a renderer by set the value
+ * of the {@link setEditRenderer EditRenderer} property to the class name of a
+ * class that implements TScaffoldEditRenderer. A renderer is an external
* template control that implements IScaffoldEditRenderer.
*
* The <b>Data</b> of the IScaffoldEditRenderer will be set as the current Active
diff --git a/framework/Data/ActiveRecord/TActiveRecord.php b/framework/Data/ActiveRecord/TActiveRecord.php index cbf02058..109ae9a6 100644 --- a/framework/Data/ActiveRecord/TActiveRecord.php +++ b/framework/Data/ActiveRecord/TActiveRecord.php @@ -1,540 +1,556 @@ <?php -/**
- * TActiveRecord class file.
- *
- * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
- * @link http://www.pradosoft.com/
- * @copyright Copyright © 2005-2007 PradoSoft
- * @license http://www.pradosoft.com/license/
- * @version $Id$
- * @package System.Data.ActiveRecord
- */
-
-Prado::using('System.Data.ActiveRecord.TActiveRecordManager');
-Prado::using('System.Data.ActiveRecord.TActiveRecordCriteria');
-
-/**
- * Base class for active records.
- *
- * An active record creates an object that wraps a row in a database table
- * or view, encapsulates the database access, and adds domain logic on that data.
- *
- * The essence of an Active Record is an object model of the
- * domain (e.g. products, items) that incorporates both behavior and
- * data in which the classes match very closely the record structure of an
- * underlying database. Each Active Record is responsible for saving and
- * loading to the database and also for any domain logic that acts on the data.
- *
- * The Active Record provides methods that do the following:
- * 1. Construct an instance of the Active Record from a SQL result set row.
- * 2. Construct a new instance for later insertion into the table.
- * 3. Finder methods to wrap commonly used SQL queries and return Active Record objects.
- * 4. Update the database and insert into it the data in the Active Record.
- *
- * Example:
- * <code>
- * class UserRecord extends TActiveRecord
- * {
- * const TABLE='users'; //optional table name.
- *
- * public $username; //corresponds to the fieldname in the table
- * public $email;
- *
- * //returns active record finder instance
- * public static function finder($className=__CLASS__)
- * {
- * return parent::finder($className);
- * }
- * }
- *
- * //create a connection and give it to the ActiveRecord manager.
- * $dsn = 'pgsql:host=localhost;dbname=test';
- * $conn = new TDbConnection($dsn, 'dbuser','dbpass');
- * TActiveRecordManager::getInstance()->setDbConnection($conn);
- *
- * //load the user record with username (primary key) 'admin'.
- * $user = UserRecord::finder()->findByPk('admin');
- * $user->email = 'admin@example.org';
- * $user->save(); //update the 'admin' record.
- * </code>
- *
- * @author Wei Zhuo <weizho[at]gmail[dot]com>
- * @version $Id$
- * @package System.Data.ActiveRecord
- * @since 3.1
- */
-abstract class TActiveRecord extends TComponent
-{
- /**
- * @var boolean true if this class is read only.
- */
- private $_readOnly=false;
-
- /**
- * @var TDbConnection database connection object.
- */
- private $_connection;
-
- /**
- * Prevent __call() method creating __sleep() when serializing.
- */
- public function __sleep()
- {
- return array_keys(get_object_vars($this));
- }
-
- /**
- * Prevent __call() method creating __wake() when unserializing.
- */
- public function __wake(){}
-
- /**
- * Create a new instance of an active record with given $data. The record
- * can be saved to the database specified by the $connection object.
- *
- * @param array optional name value pair record data.
- * @param TDbConnection optional database connection this object record use.
- */
- public function __construct($data=array(), $connection=null)
- {
- $this->copyFrom($data);
- if($connection!==null)
- $this->_connection=$connection;
- }
-
- /**
- * Copies data from an array or another object.
- * @throws TActiveRecordException if data is not array or not object.
- * @return TActiveRecord current instance.
- */
- public function copyFrom($data)
- {
- $data = is_object($data) ? get_object_vars($data) : $data;
- if(!is_array($data))
- throw new TActiveRecordException('ar_must_copy_from_array_or_object', get_class($this));
- foreach($data as $name=>$value)
- $this->$name = $value;
- return $this;
- }
-
- /**
- * Gets the current Db connection, the connection object is obtained from
- * the TActiveRecordManager if connection is currently null.
- * @return TDbConnection current db connection for this object.
- */
- public function getDbConnection()
- {
- if($this->_connection===null)
- $this->_connection=self::getRecordManager()->getDbConnection();
- if($this->_connection===null) //check it
- throw new TActiveRecordException('ar_invalid_db_connection',get_class($this));
- return $this->_connection;
- }
-
- /**
- * @param TDbConnection db connection object for this record.
- */
- public function setDbConnection($connection)
- {
- $this->_connection=$connection;
- }
-
- /**
- * Returns the instance of a active record finder for a particular class.
- * @param string active record class name.
- * @return TActiveRecord active record finder instance.
- * @throws TActiveRecordException if class name equals 'TActiveRecord'.
- */
- public static function finder($className=__CLASS__)
- {
- if($className==='TActiveRecord')
- throw new TActiveRecordException('ar_invalid_finder_class_name');
-
- static $finders = array();
- if(!isset($finders[$className]))
- {
- $f = Prado::createComponent($className);
- $f->_readOnly=true;
- $finders[$className]=$f;
- }
- return $finders[$className];
- }
-
- /**
- * Gets the record manager for this object, the default is to call
- * TActiveRecordManager::getInstance().
- * @return TActiveRecordManager default active record manager.
- */
- public function getRecordManager()
- {
- return TActiveRecordManager::getInstance();
- }
-
- /**
- * Saves the current record to the database, insert or update is automatically determined.
- * @return boolean true if record was saved successfully, false otherwise.
- */
- public function save()
- {
- return $this->commitChanges();
- }
-
- /**
- * Commit changes to the record, may insert, update or delete depending
- * on the record state given in TObjectStateRegistery.
- * @return boolean true if changes were made.
- */
- protected function commitChanges()
- {
- $registry = $this->getRecordManager()->getObjectStateRegistry();
- $gateway = $this->getRecordManager()->getRecordGateway();
- if(!$this->_readOnly)
- $this->_readOnly = $gateway->getMetaData($this)->getIsView();
- if($this->_readOnly)
- throw new TActiveRecordException('ar_readonly_exception',get_class($this));
- return $registry->commit($this,$gateway);
- }
-
- /**
- * Deletes the current record from the database. Once deleted, this object
- * can not be saved again in the same instance.
- * @return boolean true if the record was deleted successfully, false otherwise.
- */
- public function delete()
- {
- $registry = $this->getRecordManager()->getObjectStateRegistry();
- $registry->registerRemoved($this);
- return $this->commitChanges();
- }
-
- /**
- * Delete records by primary key. Usage:
- *
- * <code>
- * $finder->deleteByPk($primaryKey); //delete 1 record
- * $finder->deleteByPk($key1,$key2,...); //delete multiple records
- * $finder->deleteByPk(array($key1,$key2,...)); //delete multiple records
- * </code>
- *
- * For composite primary keys (determined from the table definitions):
- * <code>
- * $finder->deleteByPk(array($key1,$key2)); //delete 1 record
- *
- * //delete multiple records
- * $finder->deleteByPk(array($key1,$key2), array($key3,$key4),...);
- *
- * //delete multiple records
- * $finder->deleteByPk(array( array($key1,$key2), array($key3,$key4), .. ));
- * </code>
- *
- * @param mixed primary key values.
- * @return int number of records deleted.
- */
- public function deleteByPk($keys)
- {
- if(func_num_args() > 1)
- $keys = func_get_args();
- $gateway = $this->getRecordManager()->getRecordGateway();
- return $gateway->deleteRecordsByPk($this,(array)$keys);
- }
-
-
- /**
- * Delete multiple records using a criteria.
- * @param string|TActiveRecordCriteria SQL condition or criteria object.
- * @param mixed parameter values.
- * @return int number of records deleted.
- */
- public function deleteAll($criteria, $parameters=array())
- {
- if(is_string($criteria))
- {
- if(!is_array($parameters) && func_num_args() > 1)
- {
- $parameters = func_get_args();
- array_shift($parameters);
- }
- $criteria=new TActiveRecordCriteria($criteria,$parameters);
- }
- $gateway = $this->getRecordManager()->getRecordGateway();
- return $gateway->deleteRecordsByCriteria($this, $criteria);
- }
-
- /**
- * Populate the record with data, registers the object as clean.
- * @param string new record name
- * @param array name value pair record data
- * @return TActiveRecord object record, null if data is empty.
- */
- protected function populateObject($type, $data)
- {
- if(empty($data)) return null;
- $registry = $this->getRecordManager()->getObjectStateRegistry();
-
- //try the cache (the cache object must be clean)
- if(!is_null($obj = $registry->getCachedInstance($data)))
- return $obj;
-
- //create and populate the object
- $obj = Prado::createComponent($type);
- foreach($data as $name => $value)
- $obj->{$name} = $value;
-
- $gateway = $this->getRecordManager()->getRecordGateway();
- $obj->_readOnly = $gateway->getMetaData($this)->getIsView();
-
- //cache it
- return $registry->addCachedInstance($data,$obj);
- }
-
- /**
- * Find one single record that matches the criteria.
- *
- * Usage:
- * <code>
- * $finder->find('username = :name AND password = :pass',
- * array(':name'=>$name, ':pass'=>$pass));
- * $finder->find('username = ? AND password = ?', array($name, $pass));
- * $finder->find('username = ? AND password = ?', $name, $pass);
- * //$criteria is of TActiveRecordCriteria
- * $finder->find($criteria); //the 2nd parameter for find() is ignored.
- * </code>
- *
- * @param string|TActiveRecordCriteria SQL condition or criteria object.
- * @param mixed parameter values.
- * @return TActiveRecord matching record object.
- */
- public function find($criteria,$parameters=array())
- {
- if(is_string($criteria))
- {
- if(!is_array($parameters) && func_num_args() > 1)
- {
- $parameters = func_get_args();
- array_shift($parameters);
- }
- $criteria=new TActiveRecordCriteria($criteria,$parameters);
- }
- $gateway = $this->getRecordManager()->getRecordGateway();
- $data = $gateway->findRecordsByCriteria($this,$criteria);
- return $this->populateObject(get_class($this), $data);
- }
-
- /**
- * Same as find() but returns an array of objects.
- *
- * @param string|TActiveRecordCriteria SQL condition or criteria object.
- * @param mixed parameter values.
- * @return array matching record objects
- */
- public function findAll($criteria=null,$parameters=array())
- {
- if(is_string($criteria))
- {
- if(!is_array($parameters) && func_num_args() > 1)
- {
- $parameters = func_get_args();
- array_shift($parameters);
- }
- $criteria=new TActiveRecordCriteria($criteria,$parameters);
- }
- $gateway = $this->getRecordManager()->getRecordGateway();
- $results = array();
- $class = get_class($this);
- foreach($gateway->findRecordsByCriteria($this,$criteria,true) as $data)
- $results[] = $this->populateObject($class,$data);
- return $results;
- }
-
- /**
- * Find one record using only the primary key or composite primary keys. Usage:
- *
- * <code>
- * $finder->findByPk($primaryKey);
- * $finder->findByPk($key1, $key2, ...);
- * $finder->findByPk(array($key1,$key2,...));
- * </code>
- *
- * @param mixed primary keys
- * @return TActiveRecord
- */
- public function findByPk($keys)
- {
- if(func_num_args() > 1)
- $keys = func_get_args();
- $gateway = $this->getRecordManager()->getRecordGateway();
- $data = $gateway->findRecordByPK($this,$keys);
- return $this->populateObject(get_class($this), $data);
- }
-
- /**
- * Find multiple records matching a list of primary or composite keys.
- *
- * For scalar primary keys:
- * <code>
- * $finder->findAllByPk($key1, $key2, ...);
- * $finder->findAllByPk(array($key1, $key2, ...));
- * </code>
- *
- * For composite keys:
- * <code>
- * $finder->findAllByPk(array($key1, $key2), array($key3, $key4), ...);
- * $finder->findAllByPk(array(array($key1, $key2), array($key3, $key4), ...));
- * </code>
- * @param mixed primary keys
- * @return array matching ActiveRecords
- */
- public function findAllByPks($keys)
- {
- if(func_num_args() > 1)
- $keys = func_get_args();
- $gateway = $this->getRecordManager()->getRecordGateway();
- $results = array();
- $class = get_class($this);
- foreach($gateway->findRecordsByPks($this,(array)$keys) as $data)
- $results[] = $this->populateObject($class,$data);
- return $results;
- }
-
- /**
- * Find records using full SQL, returns corresponding record object.
- * The names of the column retrieved must be defined in your Active Record
- * class.
- * @param string select SQL
- * @param array $parameters
- * @return array matching active records.
- */
- public function findBySql($sql,$parameters=array())
- {
- if(!is_array($parameters) && func_num_args() > 1)
- {
- $parameters = func_get_args();
- array_shift($parameters);
- }
- $gateway = $this->getRecordManager()->getRecordGateway();
- $data = $gateway->findRecordsBySql($this,$sql,$parameters);
- $results = array();
- $class = get_class($this);
- foreach($gateway->findRecordsBySql($this,$sql,$parameters) as $data)
- $results[] = $this->populateObject($class,$data);
- return $results;
- }
-
- /**
- * Find the number of records.
- * @param string|TActiveRecordCriteria SQL condition or criteria object.
- * @param mixed parameter values.
- * @return int number of records.
- */
- public function count($criteria=null,$parameters=array())
- {
- if(is_string($criteria))
- {
- if(!is_array($parameters) && func_num_args() > 1)
- {
- $parameters = func_get_args();
- array_shift($parameters);
- }
- $criteria=new TActiveRecordCriteria($criteria,$parameters);
- }
- $gateway = $this->getRecordManager()->getRecordGateway();
- return $gateway->countRecords($this,$criteria);
- }
-
- /**
- * Dynamic find method using parts of method name as search criteria.
- * Method name starting with "findBy" only returns 1 record.
- * Method name starting with "findAllBy" returns 0 or more records.
- * Method name starting with "deleteBy" deletes records by the trail criteria.
- * The condition is taken as part of the method name after "findBy", "findAllBy"
- * or "deleteBy".
- *
- * The following are equivalent:
- * <code>
- * $finder->findByName($name)
- * $finder->find('Name = ?', $name);
- * </code>
- * <code>
- * $finder->findByUsernameAndPassword($name,$pass); // OR may be used
- * $finder->findBy_Username_And_Password($name,$pass); // _OR_ may be used
- * $finder->find('Username = ? AND Password = ?', $name, $pass);
- * </code>
- * <code>
- * $finder->findAllByAge($age);
- * $finder->findAll('Age = ?', $age);
- * </code>
- * <code>
- * $finder->deleteAll('Name = ?', $name);
- * $finder->deleteByName($name);
- * </code>
- * @return mixed single record if method name starts with "findBy", 0 or more records
- * if method name starts with "findAllBy"
- */
- public function __call($method,$args)
- {
- $delete =false;
- if($findOne = substr(strtolower($method),0,6)==='findby')
- $condition = $method[6]==='_' ? substr($method,7) : substr($method,6);
- else if(substr(strtolower($method),0,9)==='findallby')
- $condition = $method[9]==='_' ? substr($method,10) : substr($method,9);
- else if($delete = substr(strtolower($method),0,8)==='deleteby')
- $condition = $method[8]==='_' ? substr($method,9) : substr($method,8);
- else
- return null;//throw new TActiveRecordException('ar_invalid_finder_method',$method);
-
- $criteria = $this->createCriteriaFromString($method, $condition, $args);
- if($delete)
- return $this->deleteAll($criteria);
- else
- return $findOne ? $this->find($criteria) : $this->findAll($criteria);
- }
-
- /**
- * @param string __call method name
- * @param string criteria conditions
- * @param array method arguments
- * @return TActiveRecordCriteria criteria created from the method name and its arguments.
- */
- private function createCriteriaFromString($method, $condition, $args)
- {
- $fields = $this->extractMatchingConditions($method, $condition);
- $args=count($args) === 1 && is_array($args[0]) ? $args[0] : $args;
- if(count($fields)>count($args))
- {
- throw new TActiveRecordException('ar_mismatch_args_exception',
- $method,count($fields),count($args));
- }
- return new TActiveRecordCriteria(implode(' ',$fields),$args);
- }
-
- /**
- * Calculates the AND/OR condition from dynamic method substrings using
- * table meta data, allows for any AND-OR combinations.
- * @param string dynamic method name
- * @param string dynamic method search criteria
- * @return array search condition substrings
- */
- private function extractMatchingConditions($method, $condition)
- {
- $meta = $this->getRecordManager()->getRecordGateway()->getMetaData($this);
- $search = implode('|', $meta->getColumnNames());
- $regexp = '/('.$search.')(and|_and_|or|_or_)?/i';
- $matches = array();
- if(!preg_match_all($regexp, strtolower($condition), $matches,PREG_SET_ORDER))
- {
- throw new TActiveRecordException('ar_mismatch_column_names',
- $method, implode(', ', $meta->getColumnNames()), $meta->getTableName());
- }
- $fields = array();
- foreach($matches as $match)
- {
- $column = $meta->getColumn($match[1]);
- $sql = $column->getName() . ' = ? ';
- if(count($match) > 2)
- $sql .= strtoupper(str_replace('_', '', $match[2]));
- $fields[] = $sql;
- }
- return $fields;
- }
+/** + * TActiveRecord and TActiveRecordEventParameter class file. + * + * @author Wei Zhuo <weizhuo[at]gmail[dot]com> + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005-2007 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Id$ + * @package System.Data.ActiveRecord + */ + +Prado::using('System.Data.ActiveRecord.TActiveRecordManager'); +Prado::using('System.Data.ActiveRecord.TActiveRecordCriteria'); + +/** + * Base class for active records. + * + * An active record creates an object that wraps a row in a database table + * or view, encapsulates the database access, and adds domain logic on that data. + * + * The essence of an Active Record is an object model of the + * domain (e.g. products, items) that incorporates both behavior and + * data in which the classes match very closely the record structure of an + * underlying database. Each Active Record is responsible for saving and + * loading to the database and also for any domain logic that acts on the data. + * + * The Active Record provides methods that do the following: + * 1. Construct an instance of the Active Record from a SQL result set row. + * 2. Construct a new instance for later insertion into the table. + * 3. Finder methods to wrap commonly used SQL queries and return Active Record objects. + * 4. Update the database and insert into it the data in the Active Record. + * + * Example: + * <code> + * class UserRecord extends TActiveRecord + * { + * const TABLE='users'; //optional table name. + * + * public $username; //corresponds to the fieldname in the table + * public $email; + * + * //returns active record finder instance + * public static function finder($className=__CLASS__) + * { + * return parent::finder($className); + * } + * } + * + * //create a connection and give it to the ActiveRecord manager. + * $dsn = 'pgsql:host=localhost;dbname=test'; + * $conn = new TDbConnection($dsn, 'dbuser','dbpass'); + * TActiveRecordManager::getInstance()->setDbConnection($conn); + * + * //load the user record with username (primary key) 'admin'. + * $user = UserRecord::finder()->findByPk('admin'); + * $user->email = 'admin@example.org'; + * $user->save(); //update the 'admin' record. + * </code> + * + * @author Wei Zhuo <weizho[at]gmail[dot]com> + * @version $Id$ + * @package System.Data.ActiveRecord + * @since 3.1 + */ +abstract class TActiveRecord extends TComponent +{ + /** + * @var boolean true if this class is read only. + */ + private $_readOnly=false; + + /** + * @var TDbConnection database connection object. + */ + private $_connection; + + /** + * Prevent __call() method creating __sleep() when serializing. + */ + public function __sleep() + { + return array_keys(get_object_vars($this)); + } + + /** + * Prevent __call() method creating __wake() when unserializing. + */ + public function __wake(){} + + /** + * Create a new instance of an active record with given $data. The record + * can be saved to the database specified by the $connection object. + * + * @param array optional name value pair record data. + * @param TDbConnection optional database connection this object record use. + */ + public function __construct($data=array(), $connection=null) + { + $this->copyFrom($data); + if($connection!==null) + $this->_connection=$connection; + } + + /** + * Copies data from an array or another object. + * @throws TActiveRecordException if data is not array or not object. + * @return TActiveRecord current instance. + */ + public function copyFrom($data) + { + $data = is_object($data) ? get_object_vars($data) : $data; + if(!is_array($data)) + throw new TActiveRecordException('ar_must_copy_from_array_or_object', get_class($this)); + foreach($data as $name=>$value) + $this->$name = $value; + return $this; + } + + /** + * Gets the current Db connection, the connection object is obtained from + * the TActiveRecordManager if connection is currently null. + * @return TDbConnection current db connection for this object. + */ + public function getDbConnection() + { + if($this->_connection===null) + $this->_connection=self::getRecordManager()->getDbConnection(); + if($this->_connection===null) //check it + throw new TActiveRecordException('ar_invalid_db_connection',get_class($this)); + return $this->_connection; + } + + /** + * @param TDbConnection db connection object for this record. + */ + public function setDbConnection($connection) + { + $this->_connection=$connection; + } + + /** + * Returns the instance of a active record finder for a particular class. + * @param string active record class name. + * @return TActiveRecord active record finder instance. + * @throws TActiveRecordException if class name equals 'TActiveRecord'. + */ + public static function finder($className=__CLASS__) + { + if($className==='TActiveRecord') + throw new TActiveRecordException('ar_invalid_finder_class_name'); + + static $finders = array(); + if(!isset($finders[$className])) + { + $f = Prado::createComponent($className); + $f->_readOnly=true; + $finders[$className]=$f; + } + return $finders[$className]; + } + + /** + * Gets the record manager for this object, the default is to call + * TActiveRecordManager::getInstance(). + * @return TActiveRecordManager default active record manager. + */ + public function getRecordManager() + { + return TActiveRecordManager::getInstance(); + } + + /** + * Saves the current record to the database, insert or update is automatically determined. + * @return boolean true if record was saved successfully, false otherwise. + */ + public function save() + { + return $this->commitChanges(); + } + + /** + * Commit changes to the record, may insert, update or delete depending + * on the record state given in TObjectStateRegistery. + * @return boolean true if changes were made. + */ + protected function commitChanges() + { + $registry = $this->getRecordManager()->getObjectStateRegistry(); + $gateway = $this->getRecordManager()->getRecordGateway(); + if(!$this->_readOnly) + $this->_readOnly = $gateway->getMetaData($this)->getIsView(); + if($this->_readOnly) + throw new TActiveRecordException('ar_readonly_exception',get_class($this)); + return $registry->commit($this,$gateway); + } + + /** + * Deletes the current record from the database. Once deleted, this object + * can not be saved again in the same instance. + * @return boolean true if the record was deleted successfully, false otherwise. + */ + public function delete() + { + $registry = $this->getRecordManager()->getObjectStateRegistry(); + $registry->registerRemoved($this); + return $this->commitChanges(); + } + + /** + * Delete records by primary key. Usage: + * + * <code> + * $finder->deleteByPk($primaryKey); //delete 1 record + * $finder->deleteByPk($key1,$key2,...); //delete multiple records + * $finder->deleteByPk(array($key1,$key2,...)); //delete multiple records + * </code> + * + * For composite primary keys (determined from the table definitions): + * <code> + * $finder->deleteByPk(array($key1,$key2)); //delete 1 record + * + * //delete multiple records + * $finder->deleteByPk(array($key1,$key2), array($key3,$key4),...); + * + * //delete multiple records + * $finder->deleteByPk(array( array($key1,$key2), array($key3,$key4), .. )); + * </code> + * + * @param mixed primary key values. + * @return int number of records deleted. + */ + public function deleteByPk($keys) + { + if(func_num_args() > 1) + $keys = func_get_args(); + $gateway = $this->getRecordManager()->getRecordGateway(); + return $gateway->deleteRecordsByPk($this,(array)$keys); + } + + + /** + * Delete multiple records using a criteria. + * @param string|TActiveRecordCriteria SQL condition or criteria object. + * @param mixed parameter values. + * @return int number of records deleted. + */ + public function deleteAll($criteria, $parameters=array()) + { + if(is_string($criteria)) + { + if(!is_array($parameters) && func_num_args() > 1) + { + $parameters = func_get_args(); + array_shift($parameters); + } + $criteria=new TActiveRecordCriteria($criteria,$parameters); + } + $gateway = $this->getRecordManager()->getRecordGateway(); + return $gateway->deleteRecordsByCriteria($this, $criteria); + } + + /** + * Populate the record with data, registers the object as clean. + * @param string new record name + * @param array name value pair record data + * @return TActiveRecord object record, null if data is empty. + */ + protected function populateObject($type, $data) + { + if(empty($data)) return null; + $registry = $this->getRecordManager()->getObjectStateRegistry(); + + //try the cache (the cache object must be clean) + if(!is_null($obj = $registry->getCachedInstance($data))) + return $obj; + + //create and populate the object + $obj = Prado::createComponent($type); + foreach($data as $name => $value) + $obj->{$name} = $value; + + $gateway = $this->getRecordManager()->getRecordGateway(); + $obj->_readOnly = $gateway->getMetaData($this)->getIsView(); + + //cache it + return $registry->addCachedInstance($data,$obj); + } + + /** + * Find one single record that matches the criteria. + * + * Usage: + * <code> + * $finder->find('username = :name AND password = :pass', + * array(':name'=>$name, ':pass'=>$pass)); + * $finder->find('username = ? AND password = ?', array($name, $pass)); + * $finder->find('username = ? AND password = ?', $name, $pass); + * //$criteria is of TActiveRecordCriteria + * $finder->find($criteria); //the 2nd parameter for find() is ignored. + * </code> + * + * @param string|TActiveRecordCriteria SQL condition or criteria object. + * @param mixed parameter values. + * @return TActiveRecord matching record object. + */ + public function find($criteria,$parameters=array()) + { + if(is_string($criteria)) + { + if(!is_array($parameters) && func_num_args() > 1) + { + $parameters = func_get_args(); + array_shift($parameters); + } + $criteria=new TActiveRecordCriteria($criteria,$parameters); + } + $gateway = $this->getRecordManager()->getRecordGateway(); + $data = $gateway->findRecordsByCriteria($this,$criteria); + return $this->populateObject(get_class($this), $data); + } + + /** + * Same as find() but returns an array of objects. + * + * @param string|TActiveRecordCriteria SQL condition or criteria object. + * @param mixed parameter values. + * @return array matching record objects + */ + public function findAll($criteria=null,$parameters=array()) + { + if(is_string($criteria)) + { + if(!is_array($parameters) && func_num_args() > 1) + { + $parameters = func_get_args(); + array_shift($parameters); + } + $criteria=new TActiveRecordCriteria($criteria,$parameters); + } + $gateway = $this->getRecordManager()->getRecordGateway(); + $results = array(); + $class = get_class($this); + foreach($gateway->findRecordsByCriteria($this,$criteria,true) as $data) + $results[] = $this->populateObject($class,$data); + return $results; + } + + /** + * Find one record using only the primary key or composite primary keys. Usage: + * + * <code> + * $finder->findByPk($primaryKey); + * $finder->findByPk($key1, $key2, ...); + * $finder->findByPk(array($key1,$key2,...)); + * </code> + * + * @param mixed primary keys + * @return TActiveRecord + */ + public function findByPk($keys) + { + if(func_num_args() > 1) + $keys = func_get_args(); + $gateway = $this->getRecordManager()->getRecordGateway(); + $data = $gateway->findRecordByPK($this,$keys); + return $this->populateObject(get_class($this), $data); + } + + /** + * Find multiple records matching a list of primary or composite keys. + * + * For scalar primary keys: + * <code> + * $finder->findAllByPk($key1, $key2, ...); + * $finder->findAllByPk(array($key1, $key2, ...)); + * </code> + * + * For composite keys: + * <code> + * $finder->findAllByPk(array($key1, $key2), array($key3, $key4), ...); + * $finder->findAllByPk(array(array($key1, $key2), array($key3, $key4), ...)); + * </code> + * @param mixed primary keys + * @return array matching ActiveRecords + */ + public function findAllByPks($keys) + { + if(func_num_args() > 1) + $keys = func_get_args(); + $gateway = $this->getRecordManager()->getRecordGateway(); + $results = array(); + $class = get_class($this); + foreach($gateway->findRecordsByPks($this,(array)$keys) as $data) + $results[] = $this->populateObject($class,$data); + return $results; + } + + /** + * Find records using full SQL, returns corresponding record object. + * The names of the column retrieved must be defined in your Active Record + * class. + * @param string select SQL + * @param array $parameters + * @return array matching active records. + */ + public function findBySql($sql,$parameters=array()) + { + if(!is_array($parameters) && func_num_args() > 1) + { + $parameters = func_get_args(); + array_shift($parameters); + } + $gateway = $this->getRecordManager()->getRecordGateway(); + $data = $gateway->findRecordsBySql($this,$sql,$parameters); + $results = array(); + $class = get_class($this); + foreach($gateway->findRecordsBySql($this,$sql,$parameters) as $data) + $results[] = $this->populateObject($class,$data); + return $results; + } + + /** + * Find the number of records. + * @param string|TActiveRecordCriteria SQL condition or criteria object. + * @param mixed parameter values. + * @return int number of records. + */ + public function count($criteria=null,$parameters=array()) + { + if(is_string($criteria)) + { + if(!is_array($parameters) && func_num_args() > 1) + { + $parameters = func_get_args(); + array_shift($parameters); + } + $criteria=new TActiveRecordCriteria($criteria,$parameters); + } + $gateway = $this->getRecordManager()->getRecordGateway(); + return $gateway->countRecords($this,$criteria); + } + + /** + * Dynamic find method using parts of method name as search criteria. + * Method name starting with "findBy" only returns 1 record. + * Method name starting with "findAllBy" returns 0 or more records. + * Method name starting with "deleteBy" deletes records by the trail criteria. + * The condition is taken as part of the method name after "findBy", "findAllBy" + * or "deleteBy". + * + * The following are equivalent: + * <code> + * $finder->findByName($name) + * $finder->find('Name = ?', $name); + * </code> + * <code> + * $finder->findByUsernameAndPassword($name,$pass); // OR may be used + * $finder->findBy_Username_And_Password($name,$pass); // _OR_ may be used + * $finder->find('Username = ? AND Password = ?', $name, $pass); + * </code> + * <code> + * $finder->findAllByAge($age); + * $finder->findAll('Age = ?', $age); + * </code> + * <code> + * $finder->deleteAll('Name = ?', $name); + * $finder->deleteByName($name); + * </code> + * @return mixed single record if method name starts with "findBy", 0 or more records + * if method name starts with "findAllBy" + */ + public function __call($method,$args) + { + $delete =false; + if($findOne = substr(strtolower($method),0,6)==='findby') + $condition = $method[6]==='_' ? substr($method,7) : substr($method,6); + else if(substr(strtolower($method),0,9)==='findallby') + $condition = $method[9]==='_' ? substr($method,10) : substr($method,9); + else if($delete = substr(strtolower($method),0,8)==='deleteby') + $condition = $method[8]==='_' ? substr($method,9) : substr($method,8); + else + return null;//throw new TActiveRecordException('ar_invalid_finder_method',$method); + + $criteria = $this->createCriteriaFromString($method, $condition, $args); + if($delete) + return $this->deleteAll($criteria); + else + return $findOne ? $this->find($criteria) : $this->findAll($criteria); + } + + /** + * @param string __call method name + * @param string criteria conditions + * @param array method arguments + * @return TActiveRecordCriteria criteria created from the method name and its arguments. + */ + private function createCriteriaFromString($method, $condition, $args) + { + $fields = $this->extractMatchingConditions($method, $condition); + $args=count($args) === 1 && is_array($args[0]) ? $args[0] : $args; + if(count($fields)>count($args)) + { + throw new TActiveRecordException('ar_mismatch_args_exception', + $method,count($fields),count($args)); + } + return new TActiveRecordCriteria(implode(' ',$fields),$args); + } + + /** + * Calculates the AND/OR condition from dynamic method substrings using + * table meta data, allows for any AND-OR combinations. + * @param string dynamic method name + * @param string dynamic method search criteria + * @return array search condition substrings + */ + private function extractMatchingConditions($method, $condition) + { + $meta = $this->getRecordManager()->getRecordGateway()->getMetaData($this); + $search = implode('|', $meta->getColumnNames()); + $regexp = '/('.$search.')(and|_and_|or|_or_)?/i'; + $matches = array(); + if(!preg_match_all($regexp, strtolower($condition), $matches,PREG_SET_ORDER)) + { + throw new TActiveRecordException('ar_mismatch_column_names', + $method, implode(', ', $meta->getColumnNames()), $meta->getTableName()); + } + $fields = array(); + foreach($matches as $match) + { + $column = $meta->getColumn($match[1]); + $sql = $column->getName() . ' = ? '; + if(count($match) > 2) + $sql .= strtoupper(str_replace('_', '', $match[2])); + $fields[] = $sql; + } + return $fields; + } } -?>
\ No newline at end of file + +/** + * TActiveRecordEventParameter class. + * + * @author Wei Zhuo <weizho[at]gmail[dot]com> + * @version $Id$ + * @package System.Data.ActiveRecord + * @since 3.1 + */ +class TActiveRecordEventParameter extends TEventParameter +{ + +} + + + +?> diff --git a/framework/Data/ActiveRecord/TActiveRecordManager.php b/framework/Data/ActiveRecord/TActiveRecordManager.php index bd672c3b..f7568b51 100644 --- a/framework/Data/ActiveRecord/TActiveRecordManager.php +++ b/framework/Data/ActiveRecord/TActiveRecordManager.php @@ -1,6 +1,6 @@ <?php /**
- * TActiveRecordManager and TActiveRecordEventParameter classes file.
+ * TActiveRecordManager class file.
*
* @author Wei Zhuo <weizhuo[at]gmail[dot]com>
* @link http://www.pradosoft.com/
@@ -222,17 +222,5 @@ class TActiveRecordManager extends TComponent }
}
-/**
- * TActiveRecordEventParameter class.
- *
- * @author Wei Zhuo <weizho[at]gmail[dot]com>
- * @version $Id$
- * @package System.Data.ActiveRecord
- * @since 3.1
- */
-class TActiveRecordEventParameter extends TEventParameter
-{
-
-}
?>
\ No newline at end of file diff --git a/framework/TApplication.php b/framework/TApplication.php index 6b5f8fbb..0d3d349a 100644 --- a/framework/TApplication.php +++ b/framework/TApplication.php @@ -189,10 +189,6 @@ class TApplication extends TComponent */ private $_service; /** - * @var TPageService page service - */ - private $_pageService; - /** * @var array list of application modules */ private $_modules=array(); |