<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>amnuts &#187; database</title>
	<atom:link href="http://blog.amnuts.com/tag/database/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.amnuts.com</link>
	<description>php projects, javascript, and... stuff.</description>
	<lastBuildDate>Fri, 07 May 2010 09:11:14 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Auto generating basic models for a Zend Framework app</title>
		<link>http://blog.amnuts.com/2008/04/11/auto-generating-basic-models-for-a-zend-framework-app/</link>
		<comments>http://blog.amnuts.com/2008/04/11/auto-generating-basic-models-for-a-zend-framework-app/#comments</comments>
		<pubDate>Fri, 11 Apr 2008 13:18:39 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Code snippets]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[models]]></category>

		<guid isPermaLink="false">http://blog.amnuts.com/2008/04/11/auto-generating-basic-models-for-a-zend-framework-app/</guid>
		<description><![CDATA[Do you have a database with foreign keys and just wish you could have something automatically create your ZF models from it? Well, today that was me. So as a little proof of concept, this is the code I came up with to do it for me&#8230;
But before we get to that, a few caveats:

It&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>Do you have a database with foreign keys and just wish you could have something automatically create your ZF models from it? Well, today that was me. So as a little proof of concept, this is the code I came up with to do it for me&#8230;</p>
<p>But before we get to that, a few caveats:</p>
<ul>
<li>It&#8217;s just a proof of concept</li>
<li>The output needs updating for proper reference names, etc.</li>
<li>Outputs everything to screen in one go and doesn&#8217;t save the files.</li>
</ul>
<p>However, it might be handy to someone, so I post it up for your comments.<br />
<span id="more-63"></span></p>
<pre class="brush: php;">&lt; ?php

require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();

$config = array(
	'host'	 =&gt; 'localhost',
	'username' =&gt; 'myusername',
	'password' =&gt; 'mypassword',
	'dbname'   =&gt; 'mydbname'
);
try {
	$db = Zend_Db::factory('pdo_mysql', $config);
} catch (Zend_Db_Exception $e) {
	echo $e-&gt;getMessage();
	die;
}

$model = &lt; &lt;&lt;EOT
&lt;?php

class %s extends Zend_Db_Table_Abstract
{
	protected \$_name = '%s';
%s
}
EOT;

$refmap_outer = &lt;&lt;&lt;EOT
	protected \$_referenceMap	= array(
%s
	);
EOT;

$refmap_inner = &lt;&lt;&lt;EOT
		'%s' =&gt; array(
			'columns'		   =&gt; array('%s'),
			'refTableClass'	 =&gt; '%s',
			'refColumns'		=&gt; array('%s')
		)
EOT;

$toTable = new Zend_Filter_Inflector(
	':tbl',
	array(':tbl' =&gt; array('Word_CamelCaseToUnderscore', 'StringToLower'))
);

$toClass = new Zend_Filter_Inflector(
	':tbl',
	array(':tbl' =&gt; array('StringToLower', 'Word_UnderscoreToCamelCase'))
);

foreach ($db-&gt;listTables() as $table) {
	$sql = &quot;
		select
			tc.constraint_name,
			kcu.table_name,
			kcu.column_name,
			kcu.referenced_table_name,
			kcu.referenced_column_name
		from
			information_schema.table_constraints tc,
			information_schema.key_column_usage kcu
		where
			tc.table_name = &quot; . $db-&gt;quote($table) . &quot;
			and tc.constraint_type = 'FOREIGN KEY'
			and kcu.constraint_name = tc.constraint_name
		&quot;;
	$keys = $db-&gt;fetchAll($sql);

	$refs = array();
	if (!empty($keys)) {
		$r = 0;
		foreach ($keys as $key) {
			$refs[] = sprintf($refmap_inner,
					'ref' . ++$r,
					$key['column_name'],
					$toClass-&gt;filter(array('tbl' =&gt; $key['referenced_table_name'])),
					$key['referenced_column_name']
				);
		}
	}
	printf($model,
		$toClass-&gt;filter(array('tbl' =&gt; $table)),
		$toTable-&gt;filter(array('tbl' =&gt; $table)),
		(!empty($refs) ? sprintf($refmap_outer, join(&quot;,\n&quot;, $refs)) : '')
	);
}
</pre>
<p>So assuming I had a database structure like:</p>
<pre class="brush: sql;">--
-- Table structure for table `users`
--
CREATE TABLE `users` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `added` datetime NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(64) NOT NULL,
  `name_first` varchar(32) NOT NULL,
  `name_last` varchar(32) NOT NULL,
  `name_nick` varchar(32) NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `user_tags`
--
CREATE TABLE `user_tags` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` int(10) UNSIGNED NOT NULL,
  `tag_user_id` int(10) UNSIGNED NOT NULL,
  `tag` varchar(24) NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `tag` (`tag`),
  KEY `fk_user_tags_user_id` (`user_id`),
  KEY `fk_user_tags_tag_user_id` (`tag_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Constraints for table `user_tags`
--
ALTER TABLE `user_tags`
  ADD CONSTRAINT `fk_user_tags_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `fk_user_tags_tag_user_id` FOREIGN KEY (`tag_user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;</pre>
<p>it would output something like:</p>
<pre class="brush: php;">&lt; ?php

class UserTags extends Zend_Db_Table_Abstract
{
	protected $_name = 'user_tags';
	protected $_referenceMap	= array(
		'ref1' =&gt; array(
			'columns'		   =&gt; array('user_id'),
			'refTableClass'	 =&gt; 'Users',
			'refColumns'		=&gt; array('id')
		),
		'ref2' =&gt; array(
			'columns'		   =&gt; array('tag_user_id'),
			'refTableClass'	 =&gt; 'Users',
			'refColumns'		=&gt; array('id')
		)
	);
}

&lt;?php

class Users extends Zend_Db_Table_Abstract
{
	protected $_name = 'users';
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.amnuts.com/2008/04/11/auto-generating-basic-models-for-a-zend-framework-app/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
