<?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"
	>

<channel>
	<title>agum &#187; PHP</title>
	<atom:link href="http://www.agum.com/web/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.agum.com/web</link>
	<description>The Web Dev Blog</description>
	<pubDate>Mon, 23 Jun 2008 10:47:45 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<item>
		<title>Parsing lines from CSV files using Regular Expression</title>
		<link>http://www.agum.com/web/2007/06/21/parsing-lines-from-csv-files-using-regular-expression/</link>
		<comments>http://www.agum.com/web/2007/06/21/parsing-lines-from-csv-files-using-regular-expression/#comments</comments>
		<pubDate>Thu, 21 Jun 2007 18:19:59 +0000</pubDate>
		<dc:creator>Bigi</dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.agum.com/web/2007/06/21/parsing-lines-from-csv-files-using-regular-expression/</guid>
		<description><![CDATA[Maybe I&#8217;m still a newbie at regular expressions, but I searched for a long time yesterday for something that actually works, failing with many code snippets that I found. I finally found something that actually works, so I am posting it here for the benefit of all.
Keep in mind that the challenging part is that [...]]]></description>
			<content:encoded><![CDATA[<p>Maybe I&#8217;m still a newbie at regular expressions, but I searched for a long time yesterday for something that actually works, failing with many code snippets that I found. I finally found something that actually works, so I am posting it here for the benefit of all.</p>
<p><span id="more-14"></span>Keep in mind that the challenging part is that commas inside quotations should not be treated as a delimiter, which seems to be where the challenge is coming from. I am posting this as a trackback to <a href="http://brentscheffler.com/blog/archives/19">a blog post I found</a>, because I am pretty much copying directly from there:</p>
<blockquote>
<pre>$expr = "/,(?=(?:[^\"]*\&#8221;[^\"]*\&#8221;)*(?![^\"]*\&#8221;))/&#8221;;</pre>
<p>Example:</p>
<pre>$matches = preg_split($expr,
           '2006-01-01, "Apples, Oranges, and Pears", $5.95');</pre>
</blockquote>
<p>(In case it wasn&#8217;t already obvious, this works on a per-line basis. Break your CSV file into lines first.)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agum.com/web/2007/06/21/parsing-lines-from-csv-files-using-regular-expression/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Separation of POST/GET requests in PHP</title>
		<link>http://www.agum.com/web/2007/06/18/separation-of-postget-requests-in-php/</link>
		<comments>http://www.agum.com/web/2007/06/18/separation-of-postget-requests-in-php/#comments</comments>
		<pubDate>Mon, 18 Jun 2007 23:26:05 +0000</pubDate>
		<dc:creator>Bigi</dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<category><![CDATA[Web apps]]></category>

		<guid isPermaLink="false">http://www.agum.com/web/2007/06/18/separation-of-postget-requests-in-php/</guid>
		<description><![CDATA[Last time we talked about MVC application design. There is something I want to write about, stemming from the topic of the last article. It is the separation of POST/GET requests in PHP web apps, which I am an advocate of. It is sort of like a VC (View-Controller) architecture.
This is strictly an application-design topic. [...]]]></description>
			<content:encoded><![CDATA[<p>Last time we talked about MVC application design. There is something I want to write about, stemming from the topic of the last article. It is the separation of POST/GET requests in PHP web apps, which I am an advocate of. It is sort of like a VC (View-Controller) architecture.</p>
<p>This is strictly an application-design topic. I&#8217;m not introducing any new fancy functions or features in PHP. It&#8217;s about how you design your web app, for better usability. (I happen to be pretty serious about web app usability, which, IMO, all software developers should be, for any software they are working on. This is why so many of my articles focus on what you could do to improve usability &#8212; it&#8217;s something too many programmers neglect.)</p>
<p><span id="more-13"></span><strong>The history of HTTP&#8217;s POST and GET requests</strong></p>
<p>I&#8217;m sure almost anyone who does web development know what POST and GET requests are. GET requests include form parameters in the query string of the request; they can get cached; they can be sent to a friend through email/IM, and so on. POST requests send parameters as part of the header in the request, and are not visible. However, when you come down to the basic technical operations, they work almost the same way: you can do just about anything you could in either method in the other one as well. (multi-part form data are a bit harder on GET, but it could be do-able)</p>
<p>The most important difference, actually, lies in the definitions &#8212; when these HTTP requests were first invented. A POST request is defined to be a request to the server that changes the state of the server. This means, for example, posting a message on a forum, uploading a file, or anything at all that changes (inserts/deletes/updates) the database, the file system, or anything else. A GET request, on the other hand, is defined as a way to retrieve information from the server without making any changes, or a &#8220;query&#8221; as they call it.</p>
<p><strong>Why does it all matter?</strong></p>
<p>Knowing the history of POST and GET requests, you should also be aware that browsers like Firefox and IE are designed with this in mind. When you attempt to Refresh a page (or going Back/Forward to it) that you got from POSTing a form, you get a warning box telling you that POST data will be sent again to the server. This is because a POST request is expected to make a change, and repeating the same request just to view the resulting page is usually not what the users intend to do, or what the developers intend for the users to do.</p>
<p>Unfortunately, on the users point-of-view, this creates a very user-unfriendly situation when web apps aren&#8217;t designed with this in mind. The average internet user does not know the difference between POST and GET requests (many won&#8217;t even be able to tell what an HTML form is), but web developers assume people know what they are doing. Your job, as a web developer, is to make it as less painful as an experience for web users as possible. Back and Forward buttons are the most commonly used features by web users, and you want to design something that works with them, not against them. This is why I&#8217;m an advocate of separating POST and GET requests in PHP.</p>
<p><strong>What do you mean by separating POST and GET requests?</strong></p>
<p>It might not be the best way to phrase it. What I mean is to make only GET requests display anything at all, and POST requests results should always redirect to another page in the form of a GET request. In other words, POST requests always only get sent to &#8220;Controller&#8221; scripts, while GET requests always only get sent to &#8220;View&#8221; scripts.</p>
<p>To make this easier to understand, I will take the example of a project I have done a few years ago, designed in this method. It is a web-based file manager that lets you upload, delete, rename, move files as well as folders.</p>
<p>No AJAX was used in this application (it wasn&#8217;t popular in 2003). All actions are sent as a new POST request to a PHP script on the server. However, there really is only one script file for the &#8220;view&#8221;, called main.php. A handful of other PHP scripts handle all the different actions. When you upload a file, a request is sent to upload.php, and this script will redirect back to main.php in the end, using a Location header.</p>
<p>To handle error messages (or success messages), I use cookies. Back to the uploading example again &#8212; before redirecting to main.php, I set a cookie with the status and message. In main.php, if a cookie is found with this information, a dialogue box displays with the message, and then the cookie gets cleared.</p>
<p>Designed this way, Back and Forward buttons may be used freely without actually corrupting the state of the server. It is true that, for example, if a page was cached, hitting Back may lead you to an old page &#8212; but at least the POST request wouldn&#8217;t be sent again (as POST is what makes changes to the server). Most of the time, implementing some sort of cache-stopping mechanism can stop this from happening. In my file manager example, even dialogue boxes work correctly (would not re-display after showing once), due to the use of cookies.</p>
<p><strong>Some final notes</strong></p>
<p>If you are interested in some additional reading, you can look at the official <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">HTTP/1.1 method definitions</a>. An interesting part of it is this:</p>
<blockquote><p>The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.</p>
<p>If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30).</p></blockquote>
<p>It looks like that you should be returning a status code of 201 if you are going to redirect to another page using a GET request, after doing your processing in your POST request. I&#8217;m actually not entirely sure what benefits do you get from doing that other than being politically correct about definitions. If anyone knows the answer to this, feel free to post a reply and enlighten me. <img src='http://www.agum.com/web/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.agum.com/web/2007/06/18/separation-of-postget-requests-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>MVC architecture in PHP development</title>
		<link>http://www.agum.com/web/2007/06/10/mvc-architecture-in-php-development/</link>
		<comments>http://www.agum.com/web/2007/06/10/mvc-architecture-in-php-development/#comments</comments>
		<pubDate>Mon, 11 Jun 2007 00:45:06 +0000</pubDate>
		<dc:creator>Bigi</dc:creator>
		
		<category><![CDATA[MVC]]></category>

		<category><![CDATA[PHP]]></category>

		<category><![CDATA[Web apps]]></category>

		<guid isPermaLink="false">http://www.agum.com/web/2007/06/10/mvc-architecture-in-php-development/</guid>
		<description><![CDATA[MVC stands for Model-View-Controller. It is a type of architecture for developing software, recently pretty popular in web applications development. In short, the three things are pretty simple. Model is what interacts with the database, it would be the backend class code for an object-oriented language like PHP, Ruby on Rails, or C++. View is [...]]]></description>
			<content:encoded><![CDATA[<p>MVC stands for Model-View-Controller. It is a type of architecture for developing software, recently pretty popular in web applications development. In short, the three things are pretty simple. Model is what interacts with the database, it would be the backend class code for an object-oriented language like PHP, Ruby on Rails, or C++. View is basically the user interface. Controller is the logic that operates everything in between.</p>
<p>They are easy to explain, but sometimes the concept is a little abstract and it&#8217;s hard to grasp for someone who doesn&#8217;t know what MVC is to begin with. To be honest, all my years in web development I never really understood exactly what MVC is, until recently when I started doing development in Ruby on Rails. In this article, I hope to explain MVC architecture development in PHP terms, so the average web apps programmer may benefit from understanding this powerful architecture.</p>
<p><span id="more-12"></span><strong>MVC and PHP development</strong></p>
<p>The reason I mentioned Ruby on Rails is because you really have to understand how to develop an application with the MVC architecture to do anything at all on RoR. (Next time, I will write another article on RoR &#8212; but this time, I&#8217;ll talk about PHP development.)</p>
<p>The Model-View-Controller separation actually makes a lot of sense, it is actually natural for a developer to divide his/her code that way when working on a reasonably large application. Java has classes, JSP and struts; Ruby on Rails has a built-in MVC structure; but even when PHP doesn&#8217;t have anything like that, it doesn&#8217;t mean you can&#8217;t do it.</p>
<p><strong>The Model</strong></p>
<p>The MVC structure is meant for reasonably-sized applications, using object-oriented coding. The Model part, in a PHP app, would usually be a class (or multiple classes). Fairly often, the class is a representation of a table you store in the database &#8212; member variables are the data columns, and member methods are operations that can be done. As an example, you might have a User class, having variables such as username, password, email address, and other things. Some of its methods might be a new user creation function, a login function, an authentication function, and a logout function.</p>
<p>Later on, we will see how User objects will be used in the Controller part of your application. The Model, in essence, tells you what methods are available &#8212; what <em>can</em> you do to the data in the database. I thought I should just clarify (if it wasn&#8217;t clear already) &#8212; this should be all PHP code, just as what you should do in OO-programming even without MVC. There should be no HTML or any kinds of outputs (redirection, etc.) here. If doing an action means that a redirection is needed or some output is needed, pass it as an argument or a return value. (It&#8217;s fairly basic programming practices, but you&#8217;d be surprised how many web apps programmers didn&#8217;t graduate with a CS degree..)</p>
<p>Here&#8217;s an example of the Model part of your code. Of course, there will be many more classes in a real application. This is just the code is the simplest form, without a lot of the details.</p>
<blockquote>
<pre>class User
{
   var $username;
   var $password;
   var $email;
   function User($u, $p, $e) // constructor
   {
      $this-&gt;username = $u;
      $this-&gt;password = $p;
      $this-&gt;email = $e;
   }
   function create()
   {
      // creates user in the db
   }
   function login()
   {
      // checks against db, does login procedures
   }
   static function authenticate($u, $p)
   {
      // checks against db
   }
   function logout()
   {
      // does logout procedures
   }
}</pre>
</blockquote>
<p><strong>The View</strong></p>
<p>The View, in the simplest words, is the user interface. However, it doesn&#8217;t mean it would be just straight HTML. Minimal PHP logic will need to be used in your application&#8217;s interface a lot of times. For example, if you were to have the main logged-in page say, &#8220;Hello, [username]!&#8221; You would certainly need some PHP code to handle that, right? That is all part of the View. Of course, all the CSS, Javascript would be part of this too.</p>
<p>It is important that whatever PHP code in here is only what needs to be used to display the interface correctly. No additional &#8220;action&#8221; code belongs to the View &#8212; that is the Controller&#8217;s job, which we&#8217;ll see next.</p>
<p>This was easy to understand, but for clarification&#8217;s sake, let&#8217;s see an example anyway. Of course, the following isn&#8217;t even valid XHTML 1.0 (it lacks a DOCTYPE, for instance), but this is just an example.</p>
<blockquote>
<pre>&lt;?php
require_once('User.php');
// makes sure user isn't already logged in
if (User::authenticate($_COOKIE['username'], $_COOKIE['password']))
{
   header(&#8221;Location:/main.php&#8221;);
   exit();
}
?&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;Please login&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Login&lt;/h1&gt;
&lt;?
if ($_GET['error'] == 1)
{
   echo &#8216;Login incorrect. Please try again.&lt;br /&gt;&#8217;;
}
?&gt;
&lt;form action=&#8221;login_action.php&#8221; method=&#8221;post&#8221;&gt;
User: &lt;input type=&#8221;text&#8221; name=&#8221;username&#8221; /&gt;&lt;br /&gt;
Pass: &lt;input type=&#8221;password&#8221; name=&#8221;password&#8221; /&gt;&lt;br /&gt;
&lt;input type=&#8221;submit&#8221; value=&#8221;Login&#8221; /&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
</blockquote>
<p><strong>The Controller</strong></p>
<p>Sometimes it is confusing to understand what the Controller needs to do, if you weren&#8217;t working on an actual application and just reading a book/an article. It would seem like the Model and the View are all you need. So let&#8217;s go back to a concrete PHP example.</p>
<p>Now imagine you have a login page setup. The login HTML form has to submit to somewhere, right? (Even if you&#8217;re using AJAX) You don&#8217;t submit directly to the Model class file (say, User.php), because that file only contains the class code, and no actual procedural code is there, so it won&#8217;t do anything. You certainly don&#8217;t submit directly back to the View file (say, login.php), even if it ends with a .php extension! Because its job is only to display the interface.</p>
<p>This is what the Controller is. Your form will submit to a file, say, login_action.php. In this file, you create an instance of the User class, running whatever initialization you need, and calling the appropriate methods that need to be run (login).</p>
<p>Some developers fall into the temptation to display outputs from the Controller, because it&#8217;s convenient. Imagine, if you had a login form, how easy is it to just print &#8220;Login incorrect&#8221; directly from the Controller PHP code? (assuming you aren&#8217;t using AJAX, for this particular example) It is an option, and I will tell you that many scripts do just that. However, to truly utilize a MVC structure&#8217;s advantage, the Controller (like the Model) should not display any HTML outputs, but rather use redirection. You may use cookies/sessions, database storage, flat file caching, or query string to the View file to store the states of your application; and then you should always let the View take care of displaying outputs, using these stored states.</p>
<p>Now let&#8217;s see an example of a Controller code.</p>
<blockquote>
<pre>&lt;?php
require_once('User.php');
// in reality, a lot more error checking needs to be done.
$currentuser = new User($_POST['username'], $_POST['password'], &#8221;);
if ($currentuser-&gt;login())
{
   // set cookies for login info
   header(&#8221;Location:/main.php&#8221;);
   exit();
}
else
{
   header(&#8221;Location:/login.php?error=1&#8243;);
   exit();
}
?&gt;</pre>
</blockquote>
<p><strong>Conclusion</strong></p>
<p>Using the MVC structure, code becomes a lot easier to understand. For other developers to join in to understand your code, as well as for yourself in the future when you come back to it after a while. Development is also a lot easier because you know exactly where to look for what piece of code. If you were going to change some message displaying in the interface, you only need to go to the View. If your database structure sees a change, such as passwords now encrypting in a different way, you only need to change your Model. The MVC architecture is very powerful and makes your object-oriented web apps development a lot more efficient.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agum.com/web/2007/06/10/mvc-architecture-in-php-development/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Controlling outputs in PHP</title>
		<link>http://www.agum.com/web/2007/05/21/controlling-outputs-in-php/</link>
		<comments>http://www.agum.com/web/2007/05/21/controlling-outputs-in-php/#comments</comments>
		<pubDate>Tue, 22 May 2007 02:42:16 +0000</pubDate>
		<dc:creator>Bigi</dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.agum.com/web/2007/05/21/controlling-outputs-in-php/</guid>
		<description><![CDATA[PHP has provided developers with many ways to control outputs, but not many scripts put them into use. Output buffering and flushing are great ways to enhance the usability of your web applications.
In a normal request sent to the web server from the browser, the web server typically responds with the header information and the [...]]]></description>
			<content:encoded><![CDATA[<p>PHP has provided developers with many ways to control outputs, but not many scripts put them into use. Output buffering and flushing are great ways to enhance the usability of your web applications.</p>
<p>In a normal request sent to the web server from the browser, the web server typically responds with the header information and the actual content requested. The header contains numerous things, including the name of the server software, the last modified date and content-type of the document,  and others. After the header comes the content. For an HTML page (or any scripts that produce HTML output), that would be the HTML source code of the page.</p>
<p><span id="more-6"></span><strong>Buffering the output of this content</strong></p>
<p>PHP provides a number of functions that let you buffer your script&#8217;s output. Normally, whatever you output is directly sent to the client immediately to be displayed on their web browser (or, rather, waiting until a fixed number of bytes to be ready before sending it out). You can change this behavior by buffering your outputs.</p>
<p>If you are familiar with C programming, this idea is similar to intercepting the output to STDOUT (imagine using pipes in the UNIX command-line to take all outputs from a program and feed it to another program). There is a list of functions in PHP, with the prefix of &#8220;ob_&#8221;, that lets you do just this &#8212; intercepting output to the client. The &#8220;ob&#8221; stands for Output Buffering.</p>
<p>Taking feedback from the comments on the last post, I don&#8217;t want to make this seem like a beginner tutorial &#8212; rather, I want to simply inform you of its capabilities and reasons to use it, and let you do more research on how to use it if you are interested.</p>
<p>The <a href="http://us2.php.net/ob_start">php.net documentation</a> has a list of output buffering functions available to you. Most of them involve around <u>get</u>ting the contents of the buffer, <u>clean</u>ing the buffer (discards the content), and <u>flush</u>ing the buffer (sends the content out and clean the buffer), or a combination of them; and of course the <u>start</u> and <u>end</u> functions. The end function must be done together with either a flush or a clean.</p>
<p><strong>Why buffer output?</strong></p>
<p>There are many reasons this could come in handy. Imagine you are printing a page containing a table of data that comes from several MySQL queries. Of course, all your queries should have error handling. Sometimes, one query in the middle of the page might fail, and you get a page with half of the data table printed, and a MySQL warning/error follows (and usually, the page stops loading). To avoid such a case, you could start output buffering and flush only at the end when everything successfully runs. When an error is encountered, simply end and clean the buffer and print an error page. Here is a quick and brief pseudo-code for a situation like that.</p>
<blockquote>
<pre>&lt;?php

ob_start();

?&gt;
Your data is below:
&lt;?

$err = 0;
for (...) {
   // complicated loop involving many things!
   mysql_query(...);
   // somehow, you run a query in each iteration.
   // this is a bad design, but just for demonstration here...
   if (error) // some error checking
   {
      $err = 1;
      break;
   }
}
if ($err)
{
   echo "..."; // print an error page here
   ob_end_clean(); // forget what was printed before
}
else
{
   ob_end_flush(); // print out data normally
}

?&gt;</pre>
</blockquote>
<p>If you intend to do this for all your scripts, there is even a setting in the php.ini configuration that let you turn on output buffering by default, saving you to do ob_start() and ob_end_*() at the beginning and end of all your scripts.</p>
<blockquote><p>output_buffering = On</p></blockquote>
<p>By default, it is set to a number like 4096. In that case, it always waits until 4kb of data is ready before sending it out. By switching it to On, you are saving all output buffer until explicitly told to flush.</p>
<p><strong>What if I want to do the opposite?</strong></p>
<p>In some cases, it becomes necessary for a developer to do the exactly opposite of that. For example, in one script, there may be a query (and the manipulation of its results) that take very long to finish. However, you want whatever that was ready to be sent to the client and printed first. (for example, even a message of &#8220;Please wait while the page loads&#8221; would be nice to see!)</p>
<p>As seen above, if PHP is configured to wait for all 4kb of data to be ready before printing, you could get &#8220;stuck&#8221; and see an empty page before this happens. Fortunately, PHP provides us a flush() function <a href="http://us.php.net/flush">[documentation]</a> that lets you do just this. However, you should be aware that there is still a possibility that the output gets &#8220;stuck&#8221;, due to a number of other reasons, quoting from the php.net documentation:</p>
<blockquote>
<ul>
<li>flush() has no effect on the buffering scheme of your web server or the browser on the client side. Thus you need to call both ob_flush() and flush() to flush the output buffers.</li>
<li>Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.</li>
<li>Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.</li>
<li>Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won&#8217;t render tables until the &lt;/table&gt; tag of the outermost table is seen.</li>
<li>Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.</li>
</ul>
</blockquote>
<p><strong>Conclusion</strong></p>
<p>Far too often, we come across interactive web sites where they encounter a database error, and the page stops in the middle with half the data printed. Other times, you are trying to access a page with tons of data waiting to be loaded, only to be treated a blank page without knowing if your internet died, or if the server is working on your page, or if your computer/browser froze.</p>
<p>With the power of the above functions, a developer should be able to have much better control on the outputs of his/her web applications. Remember, the design of software should be user-oriented. Keep confusions and annoyances to a minimum!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agum.com/web/2007/05/21/controlling-outputs-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Inheritance to improve performance</title>
		<link>http://www.agum.com/web/2007/05/17/inheritance-to-improve-performance/</link>
		<comments>http://www.agum.com/web/2007/05/17/inheritance-to-improve-performance/#comments</comments>
		<pubDate>Thu, 17 May 2007 23:24:57 +0000</pubDate>
		<dc:creator>Bigi</dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.agum.com/web/2007/05/17/inheritance-to-improve-performance/</guid>
		<description><![CDATA[For those of you who went through a CS major in college, you probably know inheritance like the back of your hand. You know how to use it, when is a good opportunity to use it, and you know why&#8230; or so you&#8217;re told.
If you are a CS student, or a fresh grad working in [...]]]></description>
			<content:encoded><![CDATA[<p>For those of you who went through a CS major in college, you probably know inheritance like the back of your hand. You know how to use it, when is a good opportunity to use it, and you know why&#8230; or so you&#8217;re told.</p>
<p>If you are a CS student, or a fresh grad working in some company as a programmer, you might be working on object-oriented code with tons of inherited classes &#8212; because you were told to do so. However when you get to work on your own projects, especially in a language like PHP, you may not think about it. After all, PHP is a web scripting language &#8212; for many small scripts, even procedural code is good enough. You may not even need to use an object-oriented design. How would inheritance come into play?</p>
<p><span id="more-5"></span><strong> Practical Inheritance</strong></p>
<p>Suppose you&#8217;re working on a huge project in PHP, writing some kind of web-based system. You&#8217;ll certainly be working with an object-oriented design in PHP.</p>
<p>Now, when I say practical inheritance, it means that you&#8217;ll actually gain something practically when using inheritance; and in our case here, what we gain is performance.</p>
<p>Imagine that you have a class called User. This class may have some 20~ member variables, and quite a few member methods.</p>
<blockquote>
<pre>class User {
   ... // member variables
   // member methods
   function Login()...
   ... // other login-related functions
   function SendMessage()...
   ... // other messaging-related functions
   // etc. etc.
}</pre>
</blockquote>
<p>When you&#8217;re closing in to completion in your system, your backend PHP code, the User class, is getting near 100kb in file size. That&#8217;s quite a bit of code!</p>
<p>In PHP, scripts are &#8220;compiled&#8221; (or &#8220;interpreted&#8221;) as they are executed. The larger the code, the longer it takes. It may not be much when you are just testing it on your development machine, but when it&#8217;s online on a high traffic site, it gets noticeable. Now, it is true that the PHP engine and the web server can optimize a lot of this by, say, caching compiled code, etc. However, you can still help performance a lot by coding nicely.</p>
<p>Now think about your frontend scripts &#8212; you&#8217;re making an instance of the User class for every GET/POST request, and calling the appropriate methods to do your work. Your frontend scripts are nice and clean, easy-to-read and everything. How nice, right? But think about this: you&#8217;re loading the entire User class code for every action taken, and that includes all the member methods that one particular action does not need at all. When a user is just logging in, you&#8217;re creating a User instance and all its methods for every action a User can do, and then calling the Login method. Your login.php might look like this&#8230;</p>
<blockquote>
<pre>... // code to process form inputs

$myUser = new User;

... // init, etc.

$myUser-&gt;Login();

... // return results</pre>
</blockquote>
<p>So let&#8217;s look at your 100kb of User class code again. You may have 4~5 methods dealing with login and logout. Another 4~5 methods for sending a message to another user, checking messages, and other things.  This is where you can help.</p>
<p>If you make a base class called BaseUser, it only needs to contain the things that every action must require. For example, all the member variables, as well as the method that authenticates the user &#8212; checking the cookies info against the database, making sure the user is logged in. Because that kind of thing needs to be done for every action.</p>
<p>Then for every other group of similar actions, you can make a subclass. A new class named LoginUser will extend from BaseUser, and contain all the login, logout methods. Another new class named MessageUser can contain the methods for sending and receiving messages. Now, you have files that look like this:</p>
<blockquote><p>baseuser.php</p>
<pre>&lt;?php

class BaseUser {
   ... // member variables
   function Authenticate() ...
}

?&gt;</pre>
</blockquote>
<blockquote><p>loginuser.php</p>
<pre>&lt;?php

require_once('baseuser.php');

class LoginUser extends BaseUser {
   ... // login methods
}

?&gt;</pre>
</blockquote>
<blockquote><p>messageuser.php</p>
<pre>&lt;?php

require_once('baseuser.php');

class MessageUser extends BaseUser {
   ... // messaging methods
}

?&gt;</pre>
</blockquote>
<p>Instead of having a file of 100kb which contains the User class code, now you have 10 files of 10kb each, with 1 containing the BaseUser class, and the other 9 containing children classes that do different things.</p>
<p>Now, in your frontend scripts, for the scripts that take care of messaging, you can just make an instance of MessageUser &#8212; and that won&#8217;t have to load all the methods for login/logout, which is not needed at all for this particular frontend script. For every action done, PHP now only needs to read 20kb of backend code instead of 100kb.</p>
<p>How about that for a practical inheritance usage? There are tons of reasons to use inheritance, like code re-use, generalization to a parent class, polymorphing to subclasses and generalizing code&#8230; They are all helpful in a &#8220;design sense&#8221;, and you might not be able to see their benefits when the programs are executed. So if you needed a better reason to use inheritance, here it is &#8212; better performance, what more can you ask for? <img src='http://www.agum.com/web/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.agum.com/web/2007/05/17/inheritance-to-improve-performance/feed/</wfw:commentRss>
		</item>
		<item>
		<title>References in PHP</title>
		<link>http://www.agum.com/web/2007/05/17/references-in-php/</link>
		<comments>http://www.agum.com/web/2007/05/17/references-in-php/#comments</comments>
		<pubDate>Thu, 17 May 2007 10:10:37 +0000</pubDate>
		<dc:creator>Bigi</dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.agum.com/web/2007/05/17/references-in-php/</guid>
		<description><![CDATA[References in PHP are important!
This is something I never paid much attention to in the past. I only started using references in my current project. I know for a fact that many less advanced PHP coders never use references, because on the php.net documentation contribution notes, there are actually people who advocate never using references [...]]]></description>
			<content:encoded><![CDATA[<p>References in PHP are important!</p>
<p>This is something I never paid much attention to in the past. I only started using references in my current project. I know for a fact that many less advanced PHP coders never use references, because on the php.net documentation contribution notes, there are actually people who advocate never using references because they are &#8220;confusing&#8221;.</p>
<p>References are not confusing at all! They work in PHP exactly as they do in C and C++. Keep in mind that references are not pointers, and if you don&#8217;t know what references are, I suggest you look it up in a tutorial elsewhere, because I won&#8217;t start explaining it, as that will probably take a whole other entry.</p>
<p><span id="more-3"></span><strong>Function arguments: Pass-by-reference?</strong></p>
<p>References are especially important in passing function arguments. Of course, you all know that to modify variables that you pass in within a function, you have to pass by reference. But that&#8217;s not the only case! Passing by references actually improves performances. You save the computer an extra step of making a copy of the variable. You may not want to do that for typical strings, integers since they are quick to copy (it&#8217;s probably safer to pass a copy in those cases &#8212; you don&#8217;t want to accidentally change their values if they are not meant to be changed); however with your own objects, you might really want to do that. Think about a case like:</p>
<blockquote>
<pre>class CustomType {
Â   ... // a hundred member variables
Â   ... // and a good number of member methods
}
$obj = new CustomType;
foobar($obj);</pre>
</blockquote>
<p>In this case, if you declare foobar normally, when the function is called, the entire object is copied for the function to use. If your script is executed million times a second in a high traffic site, you can improve performance greatly by simplying declaring your function this way:</p>
<blockquote>
<pre>function foobar(&amp;$myObj) {
Â   ...
}</pre>
</blockquote>
<p>It is true that the function will be able to modify the object (so be careful!), but this will optimize your code by quite a bit.</p>
<p><strong>Call-time pass-by-reference</strong></p>
<p>But there&#8217;s something you want to watch out for: when passing by reference, have your <em>function take in arguments as reference</em>. That is, declare your function foobar like above, and when you call it, simply pass a regular variable to it.</p>
<p>If you do it the other way around, like this:</p>
<blockquote>
<pre>function foobar($myObj) {
Â   ...
}
$obj = new CustomType;
foobar(&amp;$obj);</pre>
</blockquote>
<p>This is called call-time pass-by-reference. And <strong><em>this is bad</em></strong>!</p>
<p>This is because whether a function argument should be passed by reference, should be a decision that belongs to the function &#8212; not the code that calls it. In fact, in the PHP configuration (php.ini), there is a setting:</p>
<blockquote><p>allow_call_time_pass_reference = Off</p></blockquote>
<p>It is set to off by default, so that whenever you do something like above, it produces a warning on the output. It serves as a reminder to tell you that it is bad!</p>
<p><strong>Some links to look at..</strong></p>
<p>Don&#8217;t know references? PHP.net has some <a href="http://us2.php.net/manual/en/language.references.whatdo.php">documentation</a> about it. Learn to use references, your code could become much more efficient!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agum.com/web/2007/05/17/references-in-php/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.467 seconds -->
