<?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>PHP Made Simple</title>
	<atom:link href="http://www.phpmadesimple.info/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.phpmadesimple.info</link>
	<description>To support simplicity, possiibility and cost effective of PHP</description>
	<lastBuildDate>Tue, 03 Aug 2010 14:13:56 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Why you should choose Yii to develop your web application</title>
		<link>http://www.phpmadesimple.info/2010/08/01/why-you-should-choose-yii-to-develop-your-web-application/</link>
		<comments>http://www.phpmadesimple.info/2010/08/01/why-you-should-choose-yii-to-develop-your-web-application/#comments</comments>
		<pubDate>Sun, 01 Aug 2010 05:10:24 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.phpmadesimple.info/?p=60</guid>
		<description><![CDATA[Our first thing when develop a web application is always about choosing the suitable framework. A framework help us to build the basic structure of the application and setting some standards as well as coding convention so that everyone in a team can work together easier.
Yii is highly OOP, well organized and extendable
At low level, [...]]]></description>
			<content:encoded><![CDATA[<p>Our first thing when develop a web application is always about choosing the suitable framework. A framework help us to build the basic structure of the application and setting some standards as well as coding convention so that everyone in a team can work together easier.</p>
<h2>Yii is highly OOP, well organized and extendable</h2>
<p>At low level, Yii wrap PHP functions into Utility classes such as CHttpRequest to manage requested URI, cookies, referrer URL, CUrlManager to parse and build urls consistently, CMap to manage array of key-value items or CPropertyValue to convert and use type-safe value.</p>
<p>It helps PHP beginner achieve the expected result using best practice code by calling one single method. It also help experienced coders save lot of time.</p>
<p>At high level, Yii use common application design patter, MVC. It breaks an application into different components such as user component, database component, error handler component, log component, etc. With the component approach:</p>
<ul>
<li>You can add or remove components to make the application more extended or lighter.</li>
<li>You can override a Yii component to modify or extend its features</li>
</ul>
<p>Yii extensions system allow community to add useful extensions such as a multi-file ajax upload, an image processor.</p>
<h2>Yii is for rapid development</h2>
<p>Yii knows the common and tedious tasks most developers are tired to deal with.</p>
<p>Use CHtml to write HTML form element faster and standardized. You will found it helpful when checking generated page with XHTML validator or when trying to reproduce user inputs in a form after submission.</p>
<p>Use Yii code generator tool, available in both command line and GUI to generate MVC elements including Model, Views and Controller classes. The generator learn from table schema basic database constraints such as type, length, allow null, etc. so data will be validated automatically before saved.</p>
<h2>Yii is configurable</h2>
<p>All application components are configurable by passing an array of properties to initialize the component. A typical configuration task is configuring DB connection. Yii configuration array using keys as property names and values as property value which is easy to guess and learn the component insight be reading the code without referring to document.</p>
<p>Yii has system-wide parameters allow you to add your custom parameters into your application and reduce hard-coded values.</p>
<h2>Yii is ready for big and complex applications</h2>
<p>In a big application you will find OOP’s concept of reusable component helpful. Reusable components make your application more manageable and testable. Developing an application with reusable components approach in mind is also more delightful and Yii supports you at different levels:</p>
<ul>
<li>Write independent utility classes so you can use them as helps in different projects and step by step make the classes bug-free and speedy</li>
<li>Add in library that your team or company use frequently like PDF generator, CSV importer, Image processor</li>
<li>Override and extend basic application components such as UrlManager, CWebApplication, CController. As a framework, Yii has to be generic in implementing these components but depend you the type of web applications your team or company build up, you can customize the components to best fit your needs.</li>
<li>Write widgets to show common HTML content and widget for common used forms such as login form, registration form, contact form, etc.</li>
<li>Break your application into modules so that common modules such as user management, back office, etc. can be reuse in other projects.</li>
</ul>
<p>Data manipulation is usually the major work in an application. Yii supports different DBMS system and also support multiple databases.</p>
<p>There are also two options for data manipulation. You can use ActiveRecord to deal with databases whose schemas are very likely to be changed many times during development time.  You can also use your optimized SQL commands to improve performance. If you do not really optimize SQL command but still think that SQL is faster than ActiveRecord, you can try caching DB schema.</p>
<p>In a complex application, Yii provide additional components to deal with advanced requirements:</p>
<ul>
<li>Log and error handler components help you log message, track the execution and handler errors the way you want, for example, sending email to someone anytime an error occurs.</li>
<li>There is user manager component to manage user session and login/logout process.</li>
<li>Yii also has 2 levels of authentication. For quick and simple authentication, you can use filters which are run before a controller action. Your filter can allow or deny user to execute an action depend on whether they are logged in or not. For complicated application which needs roles and role base access control, Yii provide RBAC authentication system.</li>
<li>Different types of caches are available in Yii. You can use CMemCache, CApcCache or CDbCache. The other cache extensions are EAccelerator, XCache, ZendDataCache. Yii provides you mechanism to cache data (variables) or generated content. You can cache part of the pages or you can cache the whole page.</li>
<li>Yii support internationalization and localization with message translation, data formatters, different views per language</li>
</ul>
<p>There are many other things we do not mention is this overview of Yii such as theming, template engine, security, web service or Ajax form, object behavior, event-driven programming. All of these capacity help to make Yii a very ideal choice for your web application framework.</p>
<p>This article is from <a title="FlexicaCMS" href="http://www.flexicacms.com" target="_blank">http://www.flexicacms.com</a> by Hudson Nguyen.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmadesimple.info/2010/08/01/why-you-should-choose-yii-to-develop-your-web-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FlexicaCMS a very potential CMS built on Yii</title>
		<link>http://www.phpmadesimple.info/2010/06/18/flexicacms-a-very-potential-cms-for-yii/</link>
		<comments>http://www.phpmadesimple.info/2010/06/18/flexicacms-a-very-potential-cms-for-yii/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 17:52:30 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.phpmadesimple.info/?p=56</guid>
		<description><![CDATA[Today I receive a post on my PHP forum about this CMS which is created by a Vietnamese company. What make me surprised is this CMS is build on Yii, a quite new PHP framework that I have written an entry about.
Yii is so great but using it in real application could be a little [...]]]></description>
			<content:encoded><![CDATA[<p>Today I receive a post on my PHP forum about this CMS which is created by a Vietnamese company. What make me surprised is this CMS is build on Yii, a quite new PHP framework that I have written an entry about.</p>
<p>Yii is so great but using it in real application could be a little challenge considering the its code base. Therefore, I keep looking for a good CMS based on Yii to be rolled out with some essential components such as a Back Office (Administrator panel), User management (with some permission would be nice) and a good method to manage site structure and navigation system. Web3CMS or dotPlan are two of the very first Yii based CMS but dotPlan is still buggy and Web3CMS looks does not look really appealing to me it has a quite simple homepage.<span id="more-56"></span></p>
<p>I got immediately excited when I check FlexicaCMS gallery on their site. Version 0.2 is even much more better than Web3CMS version 1.x.x with a demo about a complete corporate site (a little bit sad that admin panel is not accessible). The gallery show FlexicaCMS has installation wizard, a nice and clean administrator zone and the most impressive thing is some screenshots showing that <a href="http://www.flexicacms.com/demo.html" target="_blank">you can edit page content right on the page without accessing to administrator zone</a>. It shows that a FlexciaCMS page is combined by many widgets (a concept of reusable component in Yii) and for each widget, you can customize it by clicking on the pencil icon on top right of the widget. The popup show widget properties that you can change and what nice is properties are not simply textboxes but also drop-down boxes for predefined options/values. I notice this is an amazing and very user friendly feature because with textboxes, you can enter anything you want or most of the case, you don&#8217;t know what to enter.</p>
<p>To be able to get more insight of FlexicaCMS, I have to download its source code and this maybe a little issue of the author. There is no zipped version but you need to know SVN or in a Windows machine you must have SVN client to download source code from their SVN. Once I installed it on my local and start exploring the Administrator Panel, it make me really impressive as these guys do make a lot of work. The site structure is managed by a hierarchical pages list, unlimited levels. It&#8217;s pretty nice that you can drag-n-drop to move pages around too. Making menus it much more easier than using Joomla as for a menu, what you need is to choose the pages you want to show in your menu. When i try on my local test, multi-level menu is possible.</p>
<p>One more feature I notice in this set of CMS components, site structure &#8211; menus &#8211; urls, is the URLs are user friendly which mean FlexicaCMS supports SEO. Each page has an URL and you simple use the friendly format to define this URL, no regex or something similar level of complexity needed to defined that part of the URL is parameter. All you need is wrap the parameter in [ ] bracket. For example, the URL of blog post page look like this: blog/[postAlias].html. Also to support SEO, I see each page has its own Seo title, meta description and meta keyword and comparing this feature with Joomla, if I am not wrong then Joomla does not has the similar feature because it does not have page concept. The menu that you click on to go to a webpage in Joomla is built on the fly using a wizard. Well, somebody will not agree with me about this but what I mean is the core of a CMS.  Of course Joomla must has dozen of SEO components.</p>
<p>It looks like FlexicaCMS try to &#8220;steal&#8221; the idea of taxonomy from Drupal. It has a category tree which in a page called Content and Structure. When expanded all category nodes, one can easily see the way things are categorized. There are a couple categories for user roles, some categories for news and some for FAQs. I wonder how this categories set make content management become confused if I create an article and assign it to a user role category but the author got me. After going around the Administrator panel for a while, I understand what the author said on their site about modules. So users or news or FAQs are modules that each of them has a setting parameter call ROOT_CATEGORY_ID which is set to a category in the system category tree. That is why when you edit or create a article in News module, you see only part of the category tree used for News. To be honest, if someone love Drupal taxonomy then he should love this &#8220;system&#8221; category tree idea. Having this category tree ready mean in your new module that you plan to add into FlexicaCMS, if you need any categorization feature then you don&#8217;t have to re-implement the category management for your modules. This is not only a tedious work but also not easy at all, considering you want to show the category in a tree view and you want your users to drag-n-drop category, reorder them or move them from one parent to the other.</p>
<p>FlexicaCMS use Yii&#8217;s standard module structure. Something similar to Joomla&#8217;s module structure and not existed in WordPress. What I like in FlexicaCMS when I look at the code of existing modules is making a module menu in Administrator is very simple. Also, each module has its own set of setting parameters in users has a GUI page in Administrator panel to manage settings. He can even delete or add new setting parameters but this feature does not make any sense to me. What if the administrator delete an important parameter ?!? This advanced feature should be limited to developers to use in development time only. Well, I have not finished exploring this interesting CMS so I might be lousy about this, who know.</p>
<p>With the same approach when I study a new CMS, what I need to do first when I start thinking about using the CMS is how can I create my module and customize something I see on the front pages. These FlexicaCMS guys do convince me as they add in the Administrator panel a tool to generate code. Holy shh&#8230; I can create a new module with some click and it looks like I can generate all the admin pages for my modules if I create DB tables and use the Admin page generator tool. This can be just a leverage of Yii generator tool but anyway, it is good as long as I do not have to type commands into the console window.</p>
<p>I have not been able to create a page and show it on front-end as checking the existing pages in FlexicaCMS sample, they all use widgets to show content but I am a little disappointed to find out that the core widget class, CmsWidget.php is encrypted. It mean unless FlexicaCMS author publish some tutorial about making widget, it will be very hard for developers to do it themselves. Luckily, the author announced in their roadmap that FlexicaCMS will be totally open source and free for personal use (non commercial or commercial products). I can&#8217;t wait until that day ! or, I may try to get the author give me a copy of encrypted files <img src='http://www.phpmadesimple.info/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  we will see.</p>
<p>In conclusion, FlexicaCMS can be considered at the first Yii based CMS and a very potential CMS. The roadmap look good if they don&#8217;t say what they are not doing ! Personally, I believe that if version 0.3, 0.4 and then 1.0 is released as an open source then not only Yii developers will consider using it but also FlexicaCMS can help Yii spread out and good OOP programmers do have more options to choose for their projects. Joomla or WP will not be the remaining option when Drupal is quite hard to learn as well as to use and definitely not fit into a tight budget.</p>
<p><em><strong>More links and information</strong></em>:</p>
<p><a href="http://www.flexicacms.com" target="_blank">FlexicaCMS</a> and its <a href="http://demo.flexicacms.com/basic/" target="_blank">demo</a>.</p>
<p><a href="http://www.webflexica.com" target="_blank">Gia Han Online Solutions</a> &#8211; established by Hudson Nguyen (Hưng Nguyễn), and before was Artermis Software LLC, is a leading company in Vietnam outsourcing web development projects on LAMP platform. The company is well-known by its technical skills and difficult examinations in job interview.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmadesimple.info/2010/06/18/flexicacms-a-very-potential-cms-for-yii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Wordpress XMLRPC services</title>
		<link>http://www.phpmadesimple.info/2009/07/05/using-wordpress-xmlrpc-services/</link>
		<comments>http://www.phpmadesimple.info/2009/07/05/using-wordpress-xmlrpc-services/#comments</comments>
		<pubDate>Sun, 05 Jul 2009 07:44:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://artemis.com.vn/blogvui/index.php/2009/07/05/using-wordpress-xmlrpc-services/</guid>
		<description><![CDATA[Wordpress is a great blogging platform. With tons of plugins available, Wordpress is quickly become a good choice not only for personal blogging purpose but also for making content oriented sites. There are also many sites want to add &#8216;blog&#8217; feature into it and WP one more time is the chosen one.
Although WP&#8217;s plugin architecture [...]]]></description>
			<content:encoded><![CDATA[<p>Wordpress is a great blogging platform. With tons of plugins available, Wordpress is quickly become a good choice not only for personal blogging purpose but also for making content oriented sites. There are also many sites want to add &#8216;blog&#8217; feature into it and WP one more time is the chosen one.</p>
<p>Although WP&#8217;s plugin architecture is really not good, the WP&#8217;s team have added in a really interesting tool that help integration between WP blog and hosting site easier. It&#8217;s XMLRPC services. Here are some scenarios if you has a WP blog and you want to integrate it with another site, you will found XMLRPC helpful:</p>
<ul>
<li>Showing latest posts/comments on the site homepage</li>
<li>Provide links to categories in your blog</li>
<li>Turning your WP blog into a collaborative environment for your site&#8217;s authors</li>
</ul>
<p><span id="more-46"></span>Off course, the 3rd scenario look very interesting especially in case your site is quite static, you need to update content by manually update HTML files or you are using some kinds of simple content management tools that do not support multiple user, authorizing process, tagging or categorizing. Though in the limitation of this post, I can only show how to use WP&#8217;s XMLRPC.</p>
<p>So, why XMLRPC why I can write direct SQL queries to get data (post, comment, category, etc.) from WP&#8217;s database ?</p>
<p>The answer is simple, <strong>do not reinvent the wheels</strong>. You can write queries for sure, but how about building friendly urls to the posts if WP change the perma link format ? Are your sure you understand the wp_terms table well enough for getting list of categories ? And are you sure to handle the logic of post status, post types, total posts in a category, etc. well ?</p>
<p>Those are enough to decide that XMLRPC must be use when an external want to get something from your WP&#8217;s blog. It&#8217;s no need to mention about the situation you run your site on one server and WP on another.</p>
<h3>Turn it on !</h3>
<p>XMLRPC is turn off by default, otherwise some wise users of your blog who has access to it can take your content away. So, turn it on with care. You know where it&#8217;s but you might not know what it&#8217;s about. Just in case you don&#8217;t remember, go to Options &gt; Writing page and check the option Enable XMLRPC.</p>
<h3>Get list of available services</h3>
<p>Now you can use XMLRPC, just get list of what services you can use. It&#8217;s provided on <a href="http://codex.wordpress.org/XML-RPC" target="_blank">WP&#8217;s codex XML RPC page</a>:</p>
<p>http://codex.wordpress.org/XML-RPC</p>
<h3>A simple usage sample</h3>
<pre class="brush: php">

include_once(&#039;wp-includes/class-IXR.php&#039;);

define(&#039;BLOG_ID&#039;, 0);
define(&#039;RPC_USERNAME&#039;, &#039;admin&#039;);
define(&#039;RPC_PASSWORD&#039;, &#039;***&#039;);

$client = new IXR_Client(&#039;http://your.blog.path/xmlrpc.php&#039;);
$client-&amp;amp;amp;gt;query(&#039;wp.getCategories&#039;, BLOG_ID, RPC_USERNAME, RPC_PASSWORD);
$categories = $client-&amp;amp;amp;gt;getResponse();

print_r($categories);</pre>
<p>To use XMLRPC services, you must create an IRX_Client object. If you want to go in deep, the implementation code of this class is in <strong>wp-includes/class-IXR.php</strong>. The server that IRX_Client object will work with is defined by your blog&#8217;s url appended by xmlrpc.php. You must initialize the $client with this url.</p>
<p>Now, to call a service, the service name is always the first param of $client-&gt;query() following by service&#8217;s parameters. Most of the time, you need to provide BLOG_ID, username and password to login.</p>
<p>the getResponse() method of IRX_Client object will return result of your query, normally an array as in this case, we get list of categories in our blog. Simple and easy !</p>
<h3>OK, but you don&#8217;t see what you need in the service list</h3>
<p>Sometimes, you don&#8217;t.  Though there are many services implemented by the WP&#8217;s team, you must know somehow to extend the list. This is simple if you are familiar with some WP functions. Firstly, open the xmlrpc.php file and search for &#8216;function wp_xmlrpc_server&#8217;. This function is a map of XMLRPC query name and the actual functions that implement the logic.</p>
<pre class="brush: php">

$this-&amp;amp;amp;gt;methods = array(
// WordPress API
&#039;wp.getUsersBlogs&#039;		=&amp;amp;amp;gt; &#039;this:wp_getUsersBlogs&#039;,
&#039;wp.getPage&#039;			=&amp;amp;amp;gt; &#039;this:wp_getPage&#039;,
&#039;wp.getPages&#039;			=&amp;amp;amp;gt; &#039;this:wp_getPages&#039;,
&#039;wp.newPage&#039;			=&amp;amp;amp;gt; &#039;this:wp_newPage&#039;,
&#039;wp.deletePage&#039;			=&amp;amp;amp;gt; &#039;this:wp_deletePage&#039;,
&#039;wp.editPage&#039;			=&amp;amp;amp;gt; &#039;this:wp_editPage&#039;,
&#039;wp.getPageList&#039;		=&amp;amp;amp;gt; &#039;this:wp_getPageList&#039;,
&#039;wp.getAuthors&#039;			=&amp;amp;amp;gt; &#039;this:wp_getAuthors&#039;,
&#039;wp.getRecentPosts&#039;     =&amp;amp;amp;gt; &#039;this:wp_getRecentPosts&#039;,
&#039;wp.getCategories&#039;		=&amp;amp;amp;gt; &#039;this:mw_getCategories&#039;,		// Alias
//Still long list of services for other blogging platforms
</pre>
<p>Just take a look of one service, for example, the wp.getCategories we use and then you know how to write yours. Here is a sample of getRecentPosts that I added in my XMLRPC:</p>
<pre class="brush: php">

function wp_getRecentPosts($args){
$this-&amp;amp;amp;gt;escape($args);

$blog_ID     = (int) $args[0];
$username  = $args[1];
$password   = $args[2];
$limit = $args[3];

if ( !$user = $this-&amp;amp;amp;gt;login($username, $password) ) {
return $this-&amp;amp;amp;gt;error;
}
$posts = wp_get_recent_posts($limit);
foreach($posts as &amp;amp;amp;amp;$post){
//use guid field as perma link
$plink = get_permalink($post[&#039;ID&#039;]);
$post[&#039;guid&#039;] = $plink;
//Get author
$author = get_userdata($post[&#039;post_author&#039;]);
$post[&#039;post_author&#039;] = $author-&amp;amp;amp;gt;user_login;
}
return $posts;
}
</pre>
<p>That is. I am sure that if you spend time to write all the get_userdata, get_permalink, wp_get_recent_post stuff, you will need day(s). But if you use XMLRPC and just in case you don&#8217;t work with WP usual, refer to <a href="http://codex.wordpress.org/Function_Reference" target="_blank">WP Codex&#8217;s functions reference</a> page for utility functions you need, you can get what you need in hours.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmadesimple.info/2009/07/05/using-wordpress-xmlrpc-services/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Yii, the new emerging framework for PHP</title>
		<link>http://www.phpmadesimple.info/2009/06/10/yii-the-new-emerging-framework-for-php/</link>
		<comments>http://www.phpmadesimple.info/2009/06/10/yii-the-new-emerging-framework-for-php/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 06:45:27 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://artemis.com.vn/blogvui/index.php/2009/06/10/yii-the-new-emerging-framework-for-php/</guid>
		<description><![CDATA[Being redesigned and rebuilt based on success of Prado, a ASP.NET like framework, Yii inherits well designed core components and utilize flexibility of PHP. 
Proven to be the fastest PHP framework, Yii helps its authors earn the second title (not official of course), beside their Prado fastest PHP web development framework.
I&#8217;ve been with Prado since [...]]]></description>
			<content:encoded><![CDATA[<p>Being redesigned and rebuilt based on success of Prado, a ASP.NET like framework, Yii inherits well designed core components and utilize flexibility of PHP. <span id="more-45"></span></p>
<p>Proven to be the fastest PHP framework, Yii helps its authors earn the second title (not official of course), beside their Prado fastest PHP web development framework.</p>
<p>I&#8217;ve been with Prado since 2006 and many websites build by my company are Prado based. Prado is a event driven, component based framework in which, everything should be wrapped as a component for reuse purpose, ease of usage, simple configuration and distribution.</p>
<p>However, share the common with many big names, Prado proved to be slow like Zend framework or Symfony. It&#8217;s also not easy for Prado to be widely used as its architect is very similar to ASP.NET, not the MVC model that PHP and Java developers be familiar with.</p>
<p>Yii is built with those lessons in mind (well, I guess <img src='http://www.phpmadesimple.info/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ). Come back to MVC model, in general Yii is very similar to CodeIgniter or CakePHP. Yii Actions, Views and Controllers are almost the same but its also keep what are proven to be good in Prado, the component and controls.</p>
<p>A Yii control is called a widget clearly defined as a data presentation. For many MVC coders, this will help while programming and we can easily mix business processing and data presenting code together.</p>
<p>A Yii component is called an extension. Extensions are encapsulated so it is simple for coders to distribute their work among community.</p>
<p>With powerful core component for database management, form processing, extension and widget structure Yii empowers developers to develop mid-size web application. Yii 1.0.3 also come with module support so large scale web application can be divided into modules.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmadesimple.info/2009/06/10/yii-the-new-emerging-framework-for-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using XML web services</title>
		<link>http://www.phpmadesimple.info/2008/09/02/using-xml-web-services/</link>
		<comments>http://www.phpmadesimple.info/2008/09/02/using-xml-web-services/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 04:36:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[soap]]></category>
		<category><![CDATA[webservice]]></category>

		<guid isPermaLink="false">http://artemis.com.vn/blogvui/index.php/2008/09/02/using-xml-web-services/</guid>
		<description><![CDATA[Web services allow you to exchange  information over HTTP using XML. When you want to find out the weather forecast, the current stock price, or the cost of a product on eBay, you can write a short script to gather that data in a format you can  easily manipulate. From a developer&#8217;s perspective, [...]]]></description>
			<content:encoded><![CDATA[<p class="docText">Web services allow you to exchange  information over HTTP using XML. When you want to find out the weather forecast, the current stock price, or the cost of a product on eBay, you can write a short script to gather that data in a format you can  easily manipulate. From a developer&#8217;s perspective, it&#8217;s as if you&#8217;re calling a  local function that returns a value.</p>
<p class="docText">Web services empowers your application with a straightforward idea that you, your team or even the whole your company cannot develop everything but can use lot of professional services for free or by paying some money. There is also the situation when you need data that your web application is not the one collecting those information. Web services, in this case, provide data collectors a mean to expand their business by selling data or by publishing data on other websites to drive more traffics or generate more purchases. <span id="more-43"></span></p>
<p class="docText">The key behind web services is platform-independent  communication by using XML and standard protocols. Your PHP script running on Apache/Linux can invoke a function written by ASP.NET on IIS/Windows or JSP on Tomcat/Solaris. There are two major types of web services: REST and SOAP. A REST request  is relatively straightforward, as they involve making an HTTP request of a  server and processing an XML document that&#8217;s returned as the response. Since  most developers are familiar with HTTP and XML, the learning curve for REST is  short and shallow.</p>
<p class="docText">The other popular web services format is SOAP, which is a W3C standard for  passing messages across the network and calling functions on remote computers.  SOAP provides developers with many options; however, this flexibility comes at a  price. SOAP is quite complex, and the full specification is large and growing.</p>
<p class="docText">Beyond REST and SOAP, there&#8217;s one other web services format  that&#8217;s relatively common, XML-RPC. XML-RPC is similar in spirit to SOAP, as it  also converts native data into a language-netural format that you can pass into  functions and receive replies. However, XML-RPC is far less complex than  SOAP.</p>
<h1 class="docText">Making real calls</h1>
<p class="docText">One of the very interesting places to learn about web services is eBay developer site and I will use eBay services to demonstrate many aspects of using web services in real. Of course, you have to goto <a href="http://developer.ebay.com" target="_blank">http://developer.ebay.com</a> and register your own account as the security key I use here is fake.</p>
<p class="docText">Just in case you are not familiar with eBay, it&#8217;s a place for users to sell their stuff, either old or brand new. In order to make it easier for sellers and buyers, eBay provide API set to let developers retrieve information about items, deals, bids, etc. The API sets are available for many programming languages of course as they are web services and the reason I use eBay is their document is perfect and me and my company was together with a client in US won eBay top prize for widget design contenst 2008.</p>
<p class="docText">For you to get first hand experience with web service, this is a <a href="http://developer.ebay.com/DevZone/shopping/docs/Concepts/ShoppingAPIGuide.html" target="_blank">good reference</a> about how web service is setup, how you call it and how to use the result on your website.</p>
<p class="docText">Now, I know that not everyone is comfortable with handling XML. While we are talking about XML web services, it&#8217;s not true that returned result must be in XML format. Well, anyway business is to make ease for consumers and eBay did it. You will see that for one service call, you can specify the return format you want which can be NV (name-value pair), XML, JSON or SOAP. That&#8217;s to encourage you taking the next step because it&#8217;s more fun to make result into use without a need of knowledge about XML parsers. Though I am sure you will need some XML parsers sooner or later.</p>
<h2 class="docText">Calling a REST method</h2>
<p class="docText">As REST is a style of web services in which you make requests using HTTP methods such as get and post, it is very easy to make a test before writing any PHP code. Open your browser with this URL:</p>
<p class="docText">http://open.api.ebay.com/shopping?version=517&amp;appid=YourAppID&amp;callname=FindItems&amp;QueryKeywords=dog&amp;ItemSort=BestMatch</p>
<p class="docText">And you should get some readable XML result if you remember to change YourAppID with a real value. Now you know what is the result of this FindItems method. Writing a PHP code for REST method is just something you already know.</p>
<pre class="brush: php">
$base = &#039;http://open.api.ebay.com/shopping&#039;;
$params = array(&#039;version&#039; =&gt; &#039;517&#039;, &#039;appid&#039; =&gt; &#039;...&#039;, &#039;callname&#039; =&gt; &#039;FindItems&#039;, &#039;QueryKeyword&#039; =&gt; &#039;dog&#039;, &#039;ItemSort&#039; =&gt; &#039;BestMatch&#039;);
$url = $base . &#039;?&#039; . http_build_query($params);
$response = file_get_contents($url); ?&gt;
</pre>
<p class="docText">or if you want to use cURL:</p>
<p class="docText">
<pre class="brush: php">
//Prepare the $url
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($c);
curl_close($c);
</pre>
<h2 class="docText">Calling a SOAP method with WSDL</h2>
</p>
<p class="docText">To call a method using SOAP, you need SoapClient object. As SOAP is strictly typed, whenever possible you want to know the method description file which is described using WSDL (Web Service Description Language) and available in .wsdl format at the service provider host.</p>
<p>$client = new SOAPClient(&#8217;http://api.example.com/service.wsdl&#8217;);</p>
<p>SOAPClient construction method let you provide other options and an important one is the service location. Although the WSDL may specify these options by itself, it&#8217;s not the case of eBay WSDL for shopping API. This code shows how to call eBay FindItems method using SOAPClient.</p>
<pre class="brush: php">
$wsdl_url =     &#039;http://developer.ebay.com/webservices/latest/ShoppingService.wsdl&#039;;

$client = new SOAPClient($wsdl_url,
array(&#039;location&#039; =&gt; &#039;http://open.api.ebay.com/shopping?&amp;callname=FindItems&amp;version=517&amp;siteid=3&amp;appid=xxx&#039;));

$result = $client-&gt;FindItems(array(                                 &#039;QueryKeywords&#039;=&gt;&#039;iphone&#039;,                                 &#039;MaxEntries&#039; =&gt; 30                                 ));
$items = $result-&gt;Item;

foreach($items as $item){
echo $item-&gt;Title.&#039;&lt;br /&gt;&#039;;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmadesimple.info/2008/09/02/using-xml-web-services/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Prototype and Scriptaculous tree</title>
		<link>http://www.phpmadesimple.info/2008/08/18/prototype-and-scriptaculous-tree/</link>
		<comments>http://www.phpmadesimple.info/2008/08/18/prototype-and-scriptaculous-tree/#comments</comments>
		<pubDate>Mon, 18 Aug 2008 03:07:09 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[treeview]]></category>

		<guid isPermaLink="false">http://artemis.com.vn/blogvui/index.php/2008/08/18/prototype-and-scriptaculous-tree/</guid>
		<description><![CDATA[After a week trying to embrace SilverStripe JS treeview, finally I had my friend send me a treeview written on Prototype and Scriptaculous, the TafelTree. There are a dozen of treeview control written in many different JS framework like ExtJS, jQuery, etc. but it takes me long time to find out an Protopye one. Good [...]]]></description>
			<content:encoded><![CDATA[<p>After a week trying to embrace SilverStripe JS treeview, finally I had my friend send me a treeview written on Prototype and Scriptaculous, the <a href="http://tafel.developpez.com/site/lang/en/install.php" target="_blank">TafelTree</a>. There are a dozen of treeview control written in many different JS framework like ExtJS, jQuery, etc. but it takes me long time to find out an Protopye one. Good news for Prototype lovers. Anyway, when your project is stick with Protype and you don&#8217;t want to add jQuery just for a tree then this is a good news.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmadesimple.info/2008/08/18/prototype-and-scriptaculous-tree/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Resize images with ImageMagic</title>
		<link>http://www.phpmadesimple.info/2008/07/01/resize-images-with-imagemagic/</link>
		<comments>http://www.phpmadesimple.info/2008/07/01/resize-images-with-imagemagic/#comments</comments>
		<pubDate>Mon, 30 Jun 2008 18:36:21 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://artemis.com.vn/blogvui/index.php/2008/07/01/resize-images-with-imagemagic/</guid>
		<description><![CDATA[I used my old Image utilities class for a long time until today taking it seriously for an e-commerce website to resize administrative uploaded images. The library use GD2 PHP module with some calculation to resize images proportionally. Unfortunately, quality is very low for big images, those are more than 1200&#215;1200 px.
Figured out that GD2 [...]]]></description>
			<content:encoded><![CDATA[<p>I used my old Image utilities class for a long time until today taking it seriously for an e-commerce website to resize administrative uploaded images. The library use GD2 PHP module with some calculation to resize images proportionally. Unfortunately, quality is very low for big images, those are more than 1200&#215;1200 px.</p>
<p>Figured out that GD2 is not good in production environment for image processing, I turned to an ImagMagic solution. Very lucky for me I found <a href="http://asido.info/about/features/" target="_blank">Asido</a>. This cool library though at its 0.0.0.1 version provides some cool features like watermark, flip, flop, resize and crop. Asido works with image processing library through its drivers. Currently, it support GD, ImageMagic (php_imagick.dll), MagicWand (php_magicwand.dll) and image magic shell.<span id="more-34"></span></p>
<p>After half day strugling with Asido, GD driver does not make any improvement. Also calling resize() in a loop get error. MagicWand is expected to be the best solution as it&#8217;s the new ImageMagic library. Actually, result images are totally blank. I don&#8217;t test ImageMagic shell driver as some host will not allow to install ImageMagic. So the last thing to count on is ImageMagic classic extension.</p>
<p>It didn&#8217;t work!!! I was really crazy with this library. Calling resize() always get error imagick_readimage() is undefined function. Another half day pass, the PECL site points out that imagick_xxx() functions are for old version of imagick. The new one use a more OOP way, Imagick::functionxxx().</p>
<p>Pheew, at the end I spend 2 hours rewrite Asido ImageMagic driver for php_imagick.dll 2.x.x and it works like a champ. The result images quality can be compared with Windows Vista Photo Manager resize tool. Love it!!!</p>
<p><a href="http://artemis.com.vn/blogvui/wp-content/uploads/2008/07/classdriverimagick_ext.php" title="Fix Asido 0.0.0.1 ImageMagic deprecated functions">Fix Asido 0.0.0.1 ImageMagic deprecated functions</a></p>
<p><a href="http://localhost/products/myblog/wp-content/uploads/2008/09/imagic_php52x.zip">Image magic for PHP 5.2.x on Windows</a></p>
<p>I ported most of Asido features in ImageMagic driver but not tested as time is not allow. If anyone can make a test and post the bug, it would really help. Asido has bug tracker and support forum but really don&#8217;t know how to post something there.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmadesimple.info/2008/07/01/resize-images-with-imagemagic/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing the Hello world application with Prado</title>
		<link>http://www.phpmadesimple.info/2008/06/26/making-the-hello-world-application-with-prado/</link>
		<comments>http://www.phpmadesimple.info/2008/06/26/making-the-hello-world-application-with-prado/#comments</comments>
		<pubDate>Thu, 26 Jun 2008 09:38:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Prado framework]]></category>
		<category><![CDATA[prado]]></category>

		<guid isPermaLink="false">http://artemis.com.vn/blogvui/index.php/2008/06/26/making-the-hello-world-application-with-prado/</guid>
		<description><![CDATA[Prado PHP framework is a really cool framework, especially for .NET programmers who are looking for solutions in PHP. Prado focus mainly in making things done than doing a single task smartly. But coder won&#8217;t have to worry about quality of their code as Prado classes are written so well already.
I&#8217;ve spent more than one [...]]]></description>
			<content:encoded><![CDATA[<p>Prado PHP framework is a really cool framework, especially for .NET programmers who are looking for solutions in PHP. Prado focus mainly in making things done than doing a single task smartly. But coder won&#8217;t have to worry about quality of their code as Prado classes are written so well already.</p>
<p>I&#8217;ve spent more than one year with Prado, seeing the community grows day by day and people who I am talking too most say Prado is good and somehow, better than Zend framework or widely use CakePHP, Code Igniter.<span id="more-32"></span></p>
<p>As Prado document is not very easy to learn and their tutorials uses SqlLite as the database, most beginners are reluctant to learn it. That&#8217;s why I create this series of Prado training.</p>
<h1>The Prado Hello, world</h1>
<p>In this app, we learn some common .NET concepts in Prado. You should have first LAMP enviroment setup and Prado 3.1.2 (latest version when this article written) downloaded.</p>
<h2>Setup your project</h2>
<p>Extract the /framework folder to your disk as the Prado application need it. I will put it at /www/framework and my appliation will be at /www/hello. This is for reference in the next step.</p>
<p>Create your project folder structure using this command line:</p>
<p><strong>php path/to/prado-cli.php -c hello </strong></p>
<p>Note that you should stand at /www to execute this command so that Prado create the /www/hello folder for you.</p>
<p>prado-cli.php also provides some usefull command-line tool like generating active-record classes from Database. You will see it later.</p>
<h2>Folder structure</h2>
<p>Like any PHP framework, Prado creates the folder structure for your application.</p>
<ul>
<li><strong>protect : </strong>is where code goes in</li>
<li><strong>assets </strong>: Prado resource files created at runtime. Must has chmod 777</li>
<li><strong>protected</strong>/<strong>runtime</strong>: Prado runtime folder contains application state, cache data, etc.</li>
<li><strong>protected</strong>/<strong>pages</strong>: configurable, store all web pages</li>
</ul>
<p>We will look at application.xml deeper in another article but first you need to know that it contains application configurables information.</p>
<p>&lt;service id=&#8221;<strong>page</strong>&#8221; class=&#8221;<strong>TPageService</strong>&#8221; <strong>DefaultPage</strong>=&#8221;<strong>Home</strong>&#8221; BasePath=&#8221;Application.pages&#8221;&gt;<br />
&#8230;<br />
&lt;/service&gt;</p>
<p>This shows some glues to you:</p>
<ul>
<li><strong>BasePath</strong>: point to <strong>protected/pages</strong> folder. Here note that Prado uses . path syntax and &#8216;Application&#8217; is mapped to folder <strong>protected</strong>.</li>
<li><strong>DefaultPage</strong>: Home is the file /protected/pages/Home.page. When you site runs, the URL is<br />
&#8230;/hellow/index.php?<strong>page</strong>=Home. However, the Home page is the default page, you don&#8217;t have to specify page paramenter.</li>
<li>&lt;service&gt; tag is used to register the service to handle user requests. Depend on the <strong>id </strong>value,Prado load the service to handle user request. Here, when the first parameter on the querystring is <strong>page</strong>, Prado load an instand of <strong>TPageService</strong> to handle request.</li>
</ul>
<p>OK, don&#8217;t wanna make you more confused about Prado configuration at this moment. Let&#8217;s go to the page and write some code.</p>
<h1>Event based programming</h1>
<p>Prado application handle user requests by handling the events. This is very similar to .NET web application where you have pages and a page has events such as Init, Load, PreRender, etc. Each controls in the page also has events. When user interacts with control, it will raise the event and you handle that event in the code to response to user request.</p>
<p>You will have to create  Home.php file in protected/pages folder if you don&#8217;t have one. The standard code template for a page class looks like this:</p>
<pre>
<pre class="brush: php">
class Home extends TPage
{
  public function onLoad($param)
  {
  }
}
 </pre>
</pre>
<p>You can see the function OnLoad($param). This is where we write code to initialize the page whenever it&#8217;s requested by users.</p>
<p>Because Prado separates PHP code and HTML template, there must be ways for your code to pass data to your template, here is the Home.page file. Open it and edit the file:</p>
<pre>&lt;html&gt;</pre>
<pre>&lt;body&gt;</pre>
<pre>&lt;com:TForm&gt;</pre>
<pre>  &lt;com:TLabel Id="lblInfo" Text="Hello" /&gt;</pre>
<pre>  &lt;com:TButton Text="Click me" OnClick="buttonClicked" /&gt;</pre>
<pre>&lt;/com:TForm&gt;</pre>
<pre>&lt;/body&gt;</pre>
<pre>&lt;/html&gt;</pre>
<p>You can run your app now and see the Hello text and the button Click me next to it. Click the button and you get an error message. This is normal as we haven&#8217;t declare the <strong>buttonClicked </strong>function to handle click event. Prado is Event based!!!</p>
<p>Our mission is 50% complete as you see the word Hello. Let&#8217;s do the 50% remain.</p>
<p>Add this code below function OnLoad in Home.php file:</p>
<pre class="brush: php">
protected function buttonClickec($sender, $param)
{
$this-&gt;lblInfor-&gt;Text = &#039;Hello, world&#039;;
}
</pre>
<p>Retest the page and you should now see expected result. Easy! isn&#8217;t it.</p>
<p>What we did is creating a function to handle an Prado control event. An event handler needs two params, $sender represents the object which fire the event and $param contains event data. Most of the time, you don&#8217;t care much about $param b/c changed data reflects in the control properties but for some events, you will have to learn what contained in the $param object/array. You have var_dump() and print_r() PHP functions with you, or you have Prado manual as your companion.</p>
<p>Talking about way to pass data from code to template, you can see that we access the label control  whose Id is lblInfo using this syntax: $this-&gt;lblInfo. You can write this because Prado will parse the template file before processing the php file. During this time, Prado creates propeties represents controls in the template.</p>
<p>A Prado control has many properties, Text is a common property for TLabel, TButton and TTextBox. Again, open Prado manual to learn more about Prado standard controls.</p>
<p>That&#8217;s all for a classic application. Now you know how to create a Prado project using prado-cli.php command line tool, see how a page is served and the events raised by a page or a control. In the next article, we will look into some Prado module, work with MySQL database using Prado ActiveRecord, ActiveRecord Scaffolding and SqlMap. We will also take a look at a very powerful control that Prado &#8220;borrows&#8221; from ASP.NET, the Repeater control, to show tabular data.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmadesimple.info/2008/06/26/making-the-hello-world-application-with-prado/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Object Oriented Programming with JavaScript &#8211; Before Prototype, jQuery or ExtJS</title>
		<link>http://www.phpmadesimple.info/2008/04/27/object-oriented-programming-with-javascript-before-prototype-jquery-or-extjs/</link>
		<comments>http://www.phpmadesimple.info/2008/04/27/object-oriented-programming-with-javascript-before-prototype-jquery-or-extjs/#comments</comments>
		<pubDate>Sun, 27 Apr 2008 10:13:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript oop]]></category>

		<guid isPermaLink="false">http://artemis.com.vn/blogvui/index.php/2008/04/27/object-oriented-programming-with-javascript-before-prototype-jquery-or-extjs/</guid>
		<description><![CDATA[Speaking a language fluently is the key to leverage that language&#8217;s power. JavaScript has a long time being considered a difficult language to learn and use, making the Web user interface less interactive and sometimes, so boring. But in recent years, AJAX term has become so popular and many JS frameworks born to facilitate the [...]]]></description>
			<content:encoded><![CDATA[<p>Speaking a language fluently is the key to leverage that language&#8217;s power. JavaScript has a long time being considered a difficult language to learn and use, making the Web user interface less interactive and sometimes, so boring. But in recent years, AJAX term has become so popular and many JS frameworks born to facilitate the power of JavaScript. Well-known JS frameworks which are the prominent on the web are Prototype, jQuery, Mootool, ExtJs and YUI.<span id="more-30"></span></p>
<p>Most of beginners will found difficulties getting start with these frameworks. Main reason is traditional JS programmers do not use JS heavily in their web applications or use it in an unorganized way, without any best practice pattern. While OOP is not an easy programming method, using it in JS is also headache because of JS syntax. Many programmers use JS in procedural programming style by creating functions and hooking them up with events.</p>
<p>When the term Web 2.0 become a standard, JS is also become a key programming skill that a web programmer need to know. The procedural JS programming should be forget and with the coming of Prototype, jQuery or other JS framework the age of JS programming began. In this post, I want to cover the basic of JS language to build a solid based for JS programmers from where they can easily taking JS frameworks into use. JavaScript can do a lot of clever things that Java and C# can&#8217;t. Some of these can help you to write better code, and some can only help you to shoot yourself in the foot more accurately! It&#8217;s worth knowing about both, either to make use of the techniques or to avoid doing them unwittingly.</p>
<h1>Objects in JavaScript</h1>
<p>JavaScript doesn&#8217;t require the use of objects or even functions. It is possible to write a JavaScript program as a single stream of text that is executed directly as it is read by the interpreter. As a program gets bigger, though, functions and objects become a tremendously useful way of organizing your code, and we recommend you use both.</p>
<p>The simplest way to create a new JavaScript object is to invoke the built-in constructor for the Object class:</p>
<p>var myObject=new Object();</p>
<p>Let&#8217;s add a property to our simple object:</p>
<p>myObject.shoeSize=&#8221;12&#8243;;</p>
<p>In a structured OO language, we would need to define a class that declared a property shoeSize or else suffer a compiler error. Not so with JavaScript. In fact, just to emphasize the array-like nature, we can also reference properties using array syntax:</p>
<p>myObject['shoeSize']=&#8221;12&#8243;;</p>
<p>This notation is clumsy for ordinary use but has the advantage that the array index is a JavaScript expression, offering a form of runtime reflection.</p>
<p>We can also add a new function to our object dynamically:</p>
<pre class="brush: javascript">

myObject.speakYourShoeSize=function(){

alert(&quot;shoe size : &quot;+this.shoeSize);

}
</pre>
<p>Or borrow a predefined function:</p>
<pre class="brush: javascript">function sayHello(){

alert(&#039;hello, my shoeSize is &#039;+this.shoeSize);

}

...

myObject.sayHello=sayHello;
</pre>
<p>Note that in assigning the predefined function, we omit the parentheses. If we were to write</p>
<p>myObject.sayHello=sayHello();</p>
<p>then we would execute the sayHello function and assign the return value, in this case null, to the sayHello property of myObject.</p>
<p>We can attach objects to other objects in order to build up complex data models and so on:</p>
<pre class="brush: javascript">

var myLibrary=new Object();

myLibrary.books=new Array();

myLibrary.books[0]=new Object();

myLibrary.books[0].title=&quot;Turnip Cultivation through the Ages&quot;;

myLibrary.books[0].authors=new Array();

var jim=new Object();

jim.name=&quot;Jim Brown&quot;;

jim.age=9;

myLibrary.books[0].authors[0]=jim;
</pre>
<p>This can quickly become tedious (often the case where turnips are involved, I&#8217;m afraid), and JavaScript offers a compact notation that we can use to assemble object graphs more quickly, known as JSON. <a href="http://artemis.com.vn/blogvui/index.php/2008/04/27/more-about-json/" target="_blank">Have a look at it now</a>.</p>
<h1>Making classes</h1>
<p>JavaScript has a concept of objects and classes but no built-in concept of inheritance. In fact, every JavaScript object is really an instance of the same base class, a class that is capable of binding member fields and functions to itself at runtime.</p>
<p>In JavaScript, then, we can write something that looks similar to the Java declaration</p>
<p>var myObj=new MyObject();</p>
<p>but we do not define a class MyObject, but rather a function with the same name. Here is a simple constructor:</p>
<pre class="brush: javascript">

function MyObject(name,size){

this.name=name;

this.size=size;

}
</pre>
<p>We can subsequently invoke it as follows:</p>
<pre class="brush: javascript">var myObj=new MyObject(&quot;tiddles&quot;,&quot;7.5 meters&quot;);

alert(&quot;size of &quot;+myObj.name+&quot; is &quot;+myObj.size);
</pre>
<p>One common idiom is to declare the function inside the constructor:</p>
<pre class="brush: javascript">function MyObject(name,size){

this.name=name;

this.size=size;

this.tellSize=function(){

alert(&quot;size of &quot;+this.name+&quot; is &quot;+this.size);

}

}

var myObj=new Object(&quot;tiddles&quot;,&quot;7.5 meters&quot;);

myObj.tellSize();
</pre>
<p>This works, but is less than ideal in two respects. First, for every instance of MyObject that we create, we create a new function. As responsible Ajax programmers, memory leaks are never far from our minds, and if we plan on creating many such objects, we should certainly avoid this idiom.</p>
<p>A prototype is a property of JavaScript objects, for which no real equivalent exists in OO languages. Functions and properties can be associated with a constructor&#8217;s prototype. The prototype and new keyword will then work together, and, when a function is invoked by new, all properties and methods of the prototype for the function are attached to the resulting object. That sounds a bit strange, but it&#8217;s simple enough in action:</p>
<pre class="brush: javascript">function MyObject(name,size){

this.name=name;

this.size=size;

}

MyObject.prototype.tellSize=function(){

alert(&quot;size of &quot;+this.name+&quot; is &quot;+this.size);

}

var myObj=new MyObject(&quot;tiddles&quot;,&quot;7.5 meters&quot;);

myObj.tellSize();
</pre>
<p>First, we declare the constructor as before, and then we add functions to the prototype. When we create an instance of the object, the function is attached. The keyword this resolves to the object instance at runtime, and all is well.</p>
<p>Note the ordering of events here. We can refer to the prototype only after the constructor function is declared, and objects will inherit from the prototype only what has already been added to it before the constructor is invoked. The prototype can be altered between invocations to the constructor, and we can attach anything to the prototype, not just a function:</p>
<pre class="brush: javascript">MyObject.prototype.color=&quot;red&quot;;

var obj1=new MyObject();

MyObject.prototype.color=&quot;blue&quot;;

MyObject.prototype.soundEffect=&quot;boOOOoing!!&quot;;

var obj2=new MyObject();
</pre>
<p>obj1 will be red, with no sound effect, and obj2 will be blue with an annoyingly cheerful sound effect! There is generally little value in altering prototypes on the fly in this way. It&#8217;s useful to know that such things can happen, but using the prototype to define class-like behavior for JavaScript objects is the safe and sure route.</p>
<p><a href="http://phrogz.net/JS/Classes/OOPinJS.html" target="_blank">More about declaring Class with prototype</a></p>
<p>Interestingly, the prototype of certain built-in classes (that is, those implemented by the browser and exposed through JavaScript, also known as host objects) can be extended, too. Let&#8217;s have a look at how that works now.</p>
<h1>Extending built-in classes</h1>
<p>Within the web browser, DOM nodes cannot be extended in the Internet Explorer browser, but other core classes work across all major browsers. Let&#8217;s take the Array class as an example and define a few useful helper functions:</p>
<pre class="brush: javascript">Array.prototype.indexOf=function(obj){

var result=-1;

for (var i=0;i&lt; this.length;i++){

if (this[i]==obj){

result=i;

break;

}

}

return result;

}
</pre>
<p>This provides an extra function to the Array object that returns the numerical index of an object in a given array, or -1 if the array doesn&#8217;t contain the object. We can build on this further, writing a convenience method to check whether an array contains an object:</p>
<pre class="brush: javascript">Array.prototype.contains=function(obj){

return (this.indexOf(obj)&gt;=0);

}
</pre>
<p>and then add another function for appending new members after optionally checking for duplicates:</p>
<pre class="brush: javascript">Array.prototype.append=function(obj,nodup){

if (!(nodup &amp;&amp; this.contains(obj))){

this[this.length]=obj;

}

}
</pre>
<p>Any Array objects created after the declaration of these functions, whether by the new operator or as part of a JSON expression, will be able to use these functions:</p>
<pre class="brush: javascript">var numbers=[1,2,3,4,5];

var got8=numbers.contains(8);

numbers.append(&quot;cheese&quot;,true);
</pre>
<h1>Reflecting on JavaScript objects</h1>
<p>In the normal course of writing code, the programmer has a clear understanding of how the objects he is dealing with are composed, that is, what their properties and methods do. In some cases, though, we need to be able to deal with completely unknown objects and discover the nature of their properties and methods before dealing with them. For example, if we are writing a logging or debugging system, we may be required to handle arbitrary objects dumped on us from the outside world. This discovery process is known as reflection, and it should be familiar to most Java and .NET programmers.</p>
<p>If we want to find out whether a JavaScript object supports a certain property or method, we can simply test for it:</p>
<pre class="brush: javascript">if (MyObject.someProperty){

...

}
</pre>
<p>This will fail, however, if MyObject.someProperty has been assigned the boolean value false, or a numerical 0, or the special value null. A more rigorous test would be to write</p>
<p>if (typeof(MyObject.someProperty) != &#8220;undefined&#8221;){</p>
<p>If we are concerned about the type of the property, we can also use the instanceof operator. This recognizes a few basic built-in types:</p>
<pre class="brush: javascript">if (myObj instanceof Array){

...

}else if (myObj instanceof Object){

...

}
</pre>
<p>as well as any class definitions that we define ourselves through constructors:</p>
<pre class="brush: javascript">if (myObj instanceof MyObject){

...

}
</pre>
<p>If you do like using instanceof to test for custom classes, be aware of a couple of &#8220;gotchas.&#8221; First, JSON doesn&#8217;t support it-anything created with JSON is either a JavaScript Object or an Array. Second, built-in objects do support inheritance among themselves. Function and Array, for example, both inherit from Object, so the order of testing matters. If we write</p>
<pre class="brush: javascript">function testType(myObj){

if (myObj instanceof Array){

alert(&quot;it&#039;s an array&quot;);

}else if (myObj instanceof Object){

alert(&quot;it&#039;s an object&quot;);

}

}

testType([1,2,3,4]);
</pre>
<p>and pass an Array through the code, we will be told-correctly-that we have an Array. If, on the other hand, we write</p>
<pre class="brush: javascript">function testType(myObj){

if (myObj instanceof Object){

alert(&quot;it&#039;s an object&quot;);

}else if (myObj instanceof Array){

alert(&quot;it&#039;s an array&quot;);

}

}

testType([1,2,3,4]);
</pre>
<p>then we will be told that we have an Object, which is also technically correct but probably not what we intended.</p>
<p>Finally, there are times when we may want to exhaustively discover all of an object&#8217;s properties and functions. We can do this using the simple for loop:</p>
<pre class="brush: javascript">function MyObject(){

this.color=&#039;red&#039;;

this.flavor=&#039;strawberry&#039;;

this.azimuth=&#039;45 degrees&#039;;

this.favoriteDog=&#039;collie&#039;;

}

var myObj=new MyObject();

var debug=&quot;discovering...\n&quot;;

for (var i in myObj){

debug+=i+&quot; -&gt; &quot;+myObj[i]+&quot;\n&quot;;

}

alert(debug);
</pre>
<p>This loop will execute four times, returning all the values set in the constructor. The for loop syntax works on built-in objects, too-the simple debug loop above produces very big alert boxes when pointed at DOM nodes!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmadesimple.info/2008/04/27/object-oriented-programming-with-javascript-before-prototype-jquery-or-extjs/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>More about JSON</title>
		<link>http://www.phpmadesimple.info/2008/04/27/more-about-json/</link>
		<comments>http://www.phpmadesimple.info/2008/04/27/more-about-json/#comments</comments>
		<pubDate>Sun, 27 Apr 2008 09:06:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[oop with json]]></category>

		<guid isPermaLink="false">http://artemis.com.vn/blogvui/index.php/2008/04/27/more-about-json/</guid>
		<description><![CDATA[After the first post, JSON Quick start, you know what JSON is and how useful it&#8217;s in AJAX applications. This is more about JSON with more examples and advanced usages.
Using JSON
The JavaScript Object Notation (JSON) is a core feature of the language. It provides a concise mechanism for creating arrays and object graphs. In order [...]]]></description>
			<content:encoded><![CDATA[<p>After the first post, JSON Quick start, you know what JSON is and how useful it&#8217;s in AJAX applications. This is more about JSON with more examples and advanced usages.<span id="more-31"></span></p>
<h1>Using JSON</h1>
<p>The JavaScript Object Notation (JSON) is a core feature of the language. It provides a concise mechanism for creating arrays and object graphs. In order to understand JSON, we need to know how JavaScript arrays work, so let&#8217;s cover the basics of them first.</p>
<p>JavaScript has a built-in Array class that can be instantiated using the new keyword:</p>
<pre class="brush: javascript">

myLibrary.books=new Array();
</pre>
<p>Arrays can have values assigned to them by number, much like a conventional C or Java array:</p>
<pre class="brush: javascript">

myLibrary.books[4]=somePredefinedBook;
</pre>
<p>Or they can be associated with a key value, like a Java Map or Python Dictionary, or, indeed, any JavaScript Object:</p>
<pre class="brush: javascript">
myLibrary.books[&quot;BestSeller&quot;]=somePredefinedBook;
</pre>
<p>This syntax is good for fine-tuning, but building a large array or object in the first place can be tedious. The shorthand for creating a numerically indexed array is to use square braces, with the entries being written as a comma-separated list of values, thus:</p>
<pre class="brush: javascript">
myLibrary.books=[predefinedBook1,predefinedBook2,predefinedBook3];
</pre>
<p>And to build a JavaScript Object, we use curly braces, with each value written as a key:value pair:</p>
<pre class="brush: javascript">
myLibrary.books={

bestSeller : predefinedBook1,

cookbook : predefinedBook2,

spaceFiller : predefinedBook3

};
</pre>
<p>In both notations, extra white space is ignored, allowing us to pretty-print for clarity. Keys can also have spaces in them, and can be quoted in the JSON notation, for example:</p>
<p>&#8220;Best Seller&#8221; : predefinedBook1,</p>
<p>We can nest JSON notations to create one-line definitions of complex object hierarchies (albeit rather a long line):</p>
<pre class="brush: javascript">
var myLibrary={

location : &quot;my house&quot;,

keywords : [ &quot;root vegetables&quot;, &quot;turnip&quot;, &quot;tedium&quot; ],

books: [

{

title : &quot;Turnip Cultivation through the Ages&quot;,

authors : [

{ name: &quot;Jim Brown&quot;, age: 9 },

{ name: &quot;Dick Turnip&quot;, age: 312 }

],

publicationDate : &quot;long ago&quot;

},

{

title : &quot;Turnip Cultivation through the Ages, vol. 2&quot;,

authors : [

{ name: &quot;Jim Brown&quot;, age: 35 }

],

publicationDate : new Date(1605,11,05)

}

]

};
</pre>
<p>Sharp-eyed readers will have noted that we populated the publication date for the second book using a JavaScript Date object. In assigning the value we can use any JavaScript code, in fact, even a function that we defined ourselves:</p>
<pre class="brush: javascript">
function gunpowderPlot(){

return new Date(1605,11,05);

}

var volNum=2;

var turnipVol2={

title : &quot;Turnip Cultivation through the Ages, vol. &quot;+volNum,

authors : [

{ name: &quot;Jim Brown&quot;, age: 35 }

],

publicationDate : gunpowderPlot()

}
</pre>
<p>We can also define member functions for our JSON-invoked objects, which can be invoked later by the object:</p>
<pre class="brush: javascript">
var turnipVol2={

title : &quot;Turnip Cultivation through the Ages, vol. &quot;+volNum,

authors : [

{ name: &quot;Jim Brown&quot;, age: 35 }

],

publicationDate : gunpowderPlot()

},

summarize:function(len){

if (!len){ len=7; }

var summary=this.title+&quot; by &quot; + this.authors[0].name +&quot; and his cronies is very boring. Z&quot;;

for (var i=0;i&lt; len;i++){

summary+=&quot;z&quot;;

}

alert(summary);

}

};

...

turnipVol2.summarize(6);
</pre>
<p>The summarize() function has all the features of a standard JavaScript function, such as parameters and a context object identified by the keyword this. Indeed, once the object is created, it is just another JavaScript object, and we can mix and match the JavaScript and JSON notations as we please. We can use JavaScript to fine-tune an object declared in JSON:</p>
<pre class="brush: javascript">
var numbers={ one:1, two:2, three:3 };

numbers.five=5;
</pre>
<p>We initially define an object using JSON syntax and then add to it using plain JavaScript. Equally, we can extend our JavaScript-created objects using JSON:</p>
<pre class="brush: javascript">
var cookbook=new Object();

cookbook.pageCount=321;

cookbook.author={

firstName: &quot;Harry&quot;,

secondName: &quot;Christmas&quot;,

birthdate: new Date(1900,2,29),

interests: [&quot;cheese&quot;,&quot;whistling&quot;,&quot;history of lighthouse keeping&quot;]

};
</pre>
<p>With the built-in JavaScript Object and Array classes and the JSON notation, we can build object hierarchies as complicated as we like, and we could get by with nothing else. JavaScript also offers a means for creating objects that provides a comforting resemblance to class definitions for OO programmers, so let&#8217;s look at this next and see what it can offer us.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmadesimple.info/2008/04/27/more-about-json/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
