Permalink
Browse files

O conventions conventions let me be thine bitch.

When DumbledORM went back home after an exciting year at Hogwarts no one recognized him because he now also has the magic of _autoload().

Major refactor of which the details are unfortunately completely obscured in this commit, due to the simple fact that nothing remains to compare against.

To aid with analyzing the patch herewith a list of the changes that were necessary to get DumbledORM to work as a Composer library:

 * added namespace DumbledORM
 * split classes into separate files following the conventional Classname.php pattern to comply with __autoload() expectations http://www.php.net/manual/en/function.autoload.php
 * moved classes to the src/__NAMESPACE__ folder as per convention
 * fixed reference faults which resulted from the namespace addition by utilizing the "use" operator instead of explicit references which aids readability IMO
 * an additional benefit to the previously mentioned strategy, it now also exposes the missing test cases not yet implemented because test.php is not "using" all the classes being provided.
 * i.o.w test.php is in the default namespace still to simulate and test usage outside of a namespace.
 * all the model entities are also still being generated under project_dir/model where they used to go and these POPOs, if you will excuse me for lack of a better acronym, can be referenced  through \User for example.
 * only change made to the code being generated was the addition of  ```use DumbledORM\BaseTable;``` required by base.php
 * autoload magic with compliments of Composer you now only have to add DumbledORM as a dependency to your own project or simply include one line: (see INSTALL)

```php

<?php
require_once [PATH to DumbledORM].'/vendor/autoload.php';

```
  • Loading branch information...
1 parent 8e12ec2 commit a0e706b1987337d746bc1f4be85b504122ed66f6 @nickl- committed May 26, 2012
View
@@ -9,7 +9,9 @@ require_once dirname(__DIR__).'/vendor/autoload.php';
restore_error_handler();
-if (in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
+use DumbledORM\Builder;
+
+if (count($argv) > 1 && in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>
Generate DumbledORM models.
@@ -24,14 +26,9 @@ Generate DumbledORM models.
<?php
} else {
-$params = array(
- 'p:' => 'prefix:',
- 'd:' => 'dir:',
-);
-$opt = getopt(implode('', array_keys($params)), $params);
-
-require('config.php');
-require('dumbledorm.php');
-Builder::generateBase($opt['p'], ($opt['d'] ? $opt['d'] : 'model'));
+$params = array('p:' => 'prefix:','d:' => 'dir:');
+$opt = getopt(implode('',array_keys($params)),$params);
+
+Builder::generateBase(@$opt['p'],(isset($opt['d'])?$opt['d']:'model'));
}
?>
@@ -1,5 +1,6 @@
<?php
namespace DumbledORM;
+
/**
*
* DumbledORM
@@ -34,203 +35,6 @@
*/
/**
- * exceptional moments defined here
- */
-class RecordNotFoundException extends Exception {}
-
-/**
- * Class for denoting sql that should be inserted into the query directly without escaping
- *
- */
-final class PlainSql {
- private $_sql;
- public function __construct($sql) { $this->_sql = $sql; }
- public function __toString() { return $this->_sql; }
-}
-
-/**
- * Builder class for required for generating base classes
- *
- */
-abstract class Builder {
-
- /**
- * simple cameCasing method
- *
- * @param string $string
- * @return string
- */
- public static function camelCase($string) {
- return ucfirst(preg_replace("/_(\w)/e","strtoupper('\\1')",strtolower($string)));
- }
-
- /**
- * simple un_camel_casing method
- *
- * @param string $string
- * @return string
- */
- public static function unCamelCase($string) {
- return strtolower(preg_replace("/(\w)([A-Z])/","\\1_\\2",$string));
- }
-
- /**
- * re/generates base classes for db schema
- *
- * @param string $prefix
- * @param string $dir
- * @return void
- */
- public static function generateBase($prefix=null,$dir='model') {
- $tables = array();
- foreach (Db::query('show tables',null,PDO::FETCH_NUM) as $row) {
- foreach (Db::query('show columns from `'.$row[0].'`') as $col) {
- if ($col['Key'] === 'PRI') {
- $tables[$row[0]]['pk'] = $col['Field']; break;
- }
- }
- }
- foreach (array_keys($tables) as $table) {
- foreach (Db::query('show columns from `'.$table.'`') as $col) {
- if (substr($col['Field'],-3,3) === '_id') {
- $rel = substr($col['Field'],0,-3);
- if (array_key_exists($rel,$tables)) {
- if ($table === "{$rel}_meta") {
- $tables[$rel]['meta']['class'] = self::camelCase($table);
- $tables[$rel]['meta']['field'] = $col['Field'];
- }
- $tables[$table]['relations'][$rel] = array('fk' => 'id', 'lk' => $col['Field']);
- $tables[$rel]['relations'][$table] = array('fk' => $col['Field'], 'lk' => 'id');
- }
- }
- }
- }
- $basetables = "<?php\nnamespace DumbledORM;\n\nspl_autoload_register(function(\$class) { @include(__DIR__.\"/\$class.class.php\"); });\n";
- foreach ($tables as $table => $conf) {
- $relations = preg_replace('/[\n\t\s]+/','',var_export((array)@$conf['relations'],true));
- $meta = isset($conf['meta']) ? "\$meta_class = '{$conf['meta']['class']}', \$meta_field = '{$conf['meta']['field']}'," : '';
- $basetables .= "class ".$prefix.self::camelCase($table)."Base extends BaseTable { protected static \$table = '$table', \$pk = '{$conf['pk']}', $meta \$relations = $relations; }\n";
- }
- @mkdir("./$dir",0777,true);
- file_put_contents("./$dir/base.php",$basetables);
- foreach (array_keys($tables) as $table) {
- $file = "./$dir/$prefix".self::camelCase($table).'.class.php';
- if (!file_exists($file)) {
- file_put_contents($file,"<?php\nnamespace DumbledORM;\n\nclass ".$prefix.self::camelCase($table).' extends '.$prefix.self::camelCase($table).'Base {}');
- }
- }
- }
-
-}
-
-/**
- * thin wrapper for PDO access
- *
- */
-abstract class Db {
-
- /**
- * singleton variable for PDO connection
- *
- */
- private static $_pdo;
-
- /**
- * singleton getter for PDO connection
- *
- * @return PDO
- */
- public static function pdo() {
- if (!self::$_pdo) {
- self::$_pdo = new PDO('mysql:host='.DbConfig::HOST.';port='.DbConfig::PORT.';dbname='.DbConfig::DBNAME, DbConfig::USER, DbConfig::PASSWORD);
- self::$_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- }
- return self::$_pdo;
- }
-
- /**
- * execute sql as a prepared statement
- *
- * @param string $sql
- * @param mixed $params
- * @return PDOStatement
- */
- public static function execute($sql,$params=null) {
-
- $params = is_array($params) ? $params : array($params);
-
- if ($params) {
- // using preg_replace_callback ensures that any inserted PlainSql
- // with ?'s in it will not be confused for replacement markers
- $sql = preg_replace_callback('/\?/',function($a) use (&$params) {
- $a = array_shift($params);
- if ($a instanceof PlainSql) {
- return $a;
- }
- $params[] = $a;
- return '?';
- },$sql);
- }
- $stmt = self::pdo()->prepare($sql);
- $stmt->execute($params);
- return $stmt;
- }
-
- /**
- * execute sql as a prepared statement and return all records
- *
- * @param string $query
- * @param mixed $params
- * @param PDO constant $fetch_style
- * @return Array
- */
- public static function query($query,$params=null,$fetch_style=PDO::FETCH_ASSOC) {
- return self::execute($query,$params)->fetchAll($fetch_style);
- }
-
- /**
- * run a query and return the results as a ResultSet of BaseTable objects
- *
- * @param BaseTable $obj
- * @param string $query
- * @param mixed $params
- * @return ResultSet
- */
- public static function hydrate(BaseTable $obj,$query,$params=null) {
- $set = array();
- foreach (self::query($query,$params) as $record) {
- $clone = clone $obj;
- $clone->hydrate($record);
- $set[$clone->getId()] = $clone;
- }
- return new ResultSet($set);
- }
-
-}
-
-/**
- * class to manage result array more effectively
- *
- */
-final class ResultSet extends ArrayIterator {
-
- /**
- * magic method for applying called methods to all members of result set
- *
- * @param string $method
- * @param Array $params
- * @return $this
- */
- public function __call($method,$params=array()) {
- foreach ($this as $obj) {
- call_user_func_array(array($obj,$method),$params);
- }
- return $this;
- }
-
-}
-
-/**
* base functionality available to all objects extending from a generated base class
*
*/
View
@@ -0,0 +1,111 @@
+<?php
+namespace DumbledORM;
+
+use PDO;
+/**
+ *
+ * DumbledORM
+ *
+ * @version 0.1.1
+ * @author Jason Mooberry <jasonmoo@me.com>
+ * @link http://github.com/jasonmoo/DumbledORM
+ * @package DumbledORM
+ *
+ * DumbledORM is a novelty PHP ORM
+ *
+ * Copyright (c) 2010 Jason Mooberry
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is furnished
+ * to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+/**
+ * Builder class for required for generating base classes
+ *
+ */
+abstract class Builder {
+
+ /**
+ * simple cameCasing method
+ *
+ * @param string $string
+ * @return string
+ */
+ public static function camelCase($string) {
+ return ucfirst(preg_replace("/_(\w)/e","strtoupper('\\1')",strtolower($string)));
+ }
+
+ /**
+ * simple un_camel_casing method
+ *
+ * @param string $string
+ * @return string
+ */
+ public static function unCamelCase($string) {
+ return strtolower(preg_replace("/(\w)([A-Z])/","\\1_\\2",$string));
+ }
+
+ /**
+ * re/generates base classes for db schema
+ *
+ * @param string $prefix
+ * @param string $dir
+ * @return void
+ */
+ public static function generateBase($prefix=null,$dir='model') {
+ $tables = array();
+ foreach (Db::query('show tables',null,PDO::FETCH_NUM) as $row) {
+ foreach (Db::query('show columns from `'.$row[0].'`') as $col) {
+ if ($col['Key'] === 'PRI') {
+ $tables[$row[0]]['pk'] = $col['Field']; break;
+ }
+ }
+ }
+ foreach (array_keys($tables) as $table) {
+ foreach (Db::query('show columns from `'.$table.'`') as $col) {
+ if (substr($col['Field'],-3,3) === '_id') {
+ $rel = substr($col['Field'],0,-3);
+ if (array_key_exists($rel,$tables)) {
+ if ($table === "{$rel}_meta") {
+ $tables[$rel]['meta']['class'] = self::camelCase($table);
+ $tables[$rel]['meta']['field'] = $col['Field'];
+ }
+ $tables[$table]['relations'][$rel] = array('fk' => 'id', 'lk' => $col['Field']);
+ $tables[$rel]['relations'][$table] = array('fk' => $col['Field'], 'lk' => 'id');
+ }
+ }
+ }
+ }
+ $basetables = "<?php\nuse DumbledORM\BaseTable;\nspl_autoload_register(function(\$class) { @include(__DIR__.\"/\$class.class.php\"); });\n";
+ foreach ($tables as $table => $conf) {
+ $relations = preg_replace('/[\n\t\s]+/','',var_export((array)@$conf['relations'],true));
+ $meta = isset($conf['meta']) ? "\$meta_class = '{$conf['meta']['class']}', \$meta_field = '{$conf['meta']['field']}'," : '';
+ $basetables .= "class ".$prefix.self::camelCase($table)."Base extends BaseTable { protected static \$table = '$table', \$pk = '{$conf['pk']}', $meta \$relations = $relations; }\n";
+ }
+ @mkdir("./$dir",0777,true);
+ file_put_contents("./$dir/base.php",$basetables);
+ foreach (array_keys($tables) as $table) {
+ $file = "./$dir/$prefix".self::camelCase($table).'.class.php';
+ if (!file_exists($file)) {
+ file_put_contents($file,"<?php\nclass ".$prefix.self::camelCase($table).' extends '.$prefix.self::camelCase($table).'Base {}');
+ }
+ }
+ }
+
+}
Oops, something went wrong.

1 comment on commit a0e706b

Owner

nickl- commented on a0e706b May 26, 2012

O conventions conventions let me be thine bitch.

When DumbledORM went back home after an exciting year at Hogwarts no one recognized him because he now also has the magic of __autoload().

Major refactor of which the details are unfortunately completely obscured in this commit, due to the simple fact that nothing remains to compare against.

To aid with analyzing the patch herewith a list of the changes that were necessary to get DumbledORM to work as a Composer library:

  • added namespace DumbledORM
  • split classes into separate files following the conventional Classname.php pattern to comply with __autoload() expectations http://www.php.net/manual/en/function.autoload.php
  • moved classes to the src/NAMESPACE folder as per convention
  • fixed reference faults which resulted from the namespace addition by utilizing the "use" operator instead of explicit references which aids readability IMO
  • an additional benefit to the previously mentioned strategy, it now also exposes the missing test cases not yet implemented because test.php is not "using" all the classes being provided.
  • i.o.w test.php is in the default namespace still to simulate and test usage outside of a namespace.
  • all the model entities are also still being generated under project_dir/model where they used to go and these POPOs, if you will excuse me for lack of a better acronym, can be referenced through \User for example.
  • only change made to the code being generated was the addition of use DumbledORM\BaseTable; required by base.php
  • autoload magic with compliments of Composer you now only have to add DumbledORM as a dependency to your own project or simply include one line: (see INSTALL)

<?php
require_once [PATH to DumbledORM].'/vendor/autoload.php'; 
Please sign in to comment.