Skip to content

Instantly share code, notes, and snippets.

@datayja
Created October 13, 2010 15:02
Show Gist options
  • Save datayja/624209 to your computer and use it in GitHub Desktop.
Save datayja/624209 to your computer and use it in GitHub Desktop.
A small example of dynamic finder methods from the Gemstone::framework
<?php
/**
* @author Pavel Lisa <[email protected]>
*
* Requires PHP 5.3+
*/
// get a singleton instance of ActiveRecord\Table
// -> there is one AR\Table instance for each table,
// given that the table is unique across all databases in the project
$records = table('records');
// perform a finder method
// WARNING: \ActiveRecord\Base is actually an abstract class with all these
// methods implemented, so you should use only your own subclasses of this Base
// class, under your own namespace.
$record = \ActiveRecord\Base::where( $records['id']->eq(1)->or( $records['id']->not_in( array( 2, 3, 4 ) ) ) );
// ...or the same as ...
$record = \ActiveRecord\Base::where(
$records['id']
->eq( 1 )
->or(
$records['id']
->not_in( range( 2, 4 ) )
)
);
// ... and many more combinations, using eq, not_eq, lt, gt, le, ge, in, like, between, connected with and, or, xor, and_not, or_not...
/* NOTES:
* The expression $records['id'] will get an instance of ActiveRecord\FinderExpression,
* which then provides these methods, while keeping a reference to the database adapter
* provided by the table() helper function. The adapter then provides all necessary escapings,
* and possibly some unescaped options to inject SQL statement directly - this feature then
* should be used with caution and not accepting user's input. If there will be such requests,
* the author of the Gemstone::framework may implement the missing expressions, like
* subqueries.
*/
// The FinderExpression then evaluates as this string:
// '( ( "records"."id" == 1 ) OR ( "records"."id" NOT IN ( 2, 3, 4 ) ) )'
// ... for SQLite3 adapter, or ...
// '( ( `records`.`id` == 1 ) OR ( `records`.`id` NOT IN ( 2, 3, 4 ) ) )'
// ... for MySQL adapter. The other adapters work similarly.
// Seek for Gemstone::framework on GitHub for more source code and give us any feedback! :)
// http://github.com/ThePablick/Gemstone-framework
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment