Buy My Book
By Quentin Zervaas
Want to assert yourself as a cutting–edge PHP web developer? Take a practical approach...
|
I've added the ability to easily submit articles blog posts to Digg. If you have a Digg account, please support this site by submitting any new content!
The more Diggs this site gets the more popular it becomes and the more articles that will be written!
As you develop web applications that make use of Ajax to dynamically load content on a web page, you might find that you also need to dynamically load a JavaScript file. The remainder of this blog post describes a function to achieve exactly this.
This function relies on the Prototype JavaScript framework, which hopefully you are using already. For more information about how to use Prototype, you should read the article series Eight Weeks of Prototype.
In order to load a JavaScript file you need to insert a new script element into the Document Object Model (DOM). While in theory this sounds relatively straightforward, you need to ensure the code has finished loading before you can make use of it.
This is achieved by observing the onload event on the <script> element. Unfortunately, doing so will work on all browsers except for Internet Explorer, which instead requires that you monitor the onreadystatechange event.
The following function allows you to easily load JavaScript files in real time.
<script type="text/javascript">
function loadJs(path, onload)
{
var script = new Element('script', {
src : path,
type : 'text/javascript'
});
if (onload) {
if (Prototype.Browser.IE) {
Event.observe(script, 'readystatechange', function(e) {
if (this.readyState == 'loading')
return;
onload();
}.bind(script));
}
else
Event.observe(script, 'load', onload.bind(script));
}
$$('head')[0].insert(script);
}
</script>
The following code shows an example of loading a file called scripts.js, in which a function called myFunction() is defined. This function is not available until the scripts.js file is loaded.
The script DOM element is passed as the first and only argument to the callback function.
<script type="text/javascript">
loadJs('/path/to/scripts.js', function(script) {
myFunction();
});
</script>
Alternatively, you could define the callback function separately, as in the following:
<script type="text/javascript">
function onScriptLoaded()
{
myFunction();
}
loadJs('/path/to/scripts.js', onScriptLoaded);
</script>
This function begins by creating the new DOM element (without yet adding it to the DOM). These four lines would be the equivalent to the HTML <script type="text/javascript" src="/path/to/file.js"></script>
Next we check whether or not a callback function has been defined (since it is optional). If the function is defined, we then check whether or not the browser is Internet Explorer.
If the browser is Internet Explorer, we observe the onreadystatechange event. This event is triggered when the file starts to load and when it has completed loading. Obviously we are only interested in when it has completed, so we check the readyState property.
For all other browsers we simply observe the onload event, which is fired only when the file has completed loading (as well as if the file is already in the browser cache).
In both cases, the Prototype bind() method is called in order to bind the script element to the callback. This means that when you refer to this in the callback, it refers to the script element.
Finally, the element is inserted into the DOM. This is done by inserting it into the head of the HTML document (retrieved using the Prototype $$() method, covered in Week 1, Beginning With Prototype.
The element should be inserted into the DOM as the final step since if it's done before observing the events, the events may be fired immediately if the file is already in the browser cache.
This post covers a number of different Prototype features, such as creating elements, selecting elements, observing elements and binding objects. Refer to the article series Eight Weeks of Prototype for more information on each of these concepts.
I have today launched the first article in my eight part series about the Prototype JavaScript framework.
There will be a new article released each week for the next seven weeks, covering a wide range of topics, such as creating classes and event handling with Prototype.
While the content of these articles is not strictly related to PHP, hopefully as PHP developers you will find them useful anyway in building your own modern day web applications. The final article in this series will cover an extensive example of using Prototype, in which PHP will be used on the server-side.
In addition to being able to read each article for free online, you can purchase a PDF copy of each article for a nominal fee ($5), or purchase the entire 8-part series for $12. If you purchase the entire series you will be notified when each subsequent article is released, allowing you to then download it.
Zend Technologies today released version 1.5.0 of its Zend Framework, which is good for developers since it brings new features and bug fixes, but more work if you try to keep your sites up-to-date with the latest version.
There are some new components available in this version, such as support for OpenID, the new Zend_Form component, and the new Zend_Layout component.
Although I haven't yet used Zend_Layout, reading through the documentation I'm finding it hard to see what real use it provides. To me it looks like an extra presentation layer that doesn't really achieve anything that can't be done using Zend_View (or a custom implementation, such as using Smarty).
The idea of Zend_Form is good, although I think if I ever use this component I would just use it for form processing and not use it to generate my HTML output. Doing so blurs the lines once again between presentation and application logic. Additionally, defining validation rules in a form processor is not always an ideal solution. For instance, if you want to use similar versions of the form on different areas of the site (such as the public area of the site and in an administration area), you may find yourself duplicating validation rules. The alternative to this would be define them in the central class that manages the respective data.
Another improvement is in the Zend_Search_Lucene component. According to the press release, "Now it is possible to implement advanced queries using wildcards, date ranges, and fuzzy searches from within a Zend Framework application". This component is extremely powerful and these new features sound like they will be really useful.
The Zend_Pdf component has been improved so it now supports UTF-8. In my own dealings with this component in prior versions, it felt like the overall component was very immature compared to other ZF components (in areas such as API/PhpDoc comments, coding style and in the official documentation). Not only that, it seemed like a lot of obvious features were missing. I'd like to be proven wrong on this as I really want to be able to use it.
Finally, there are notes about the Gdata (used for Google services) handling being improved. While improvements are good, my general feeling on all these third-party services in Zend Framework is simply that they shouldn't be in there. The ZF should provide the tools to solve problems, it shouldn't solve specific problems such as how to communicate with Google, Amazon, Delicious, Flickr or Yahoo!.
The PHP 5 Iterator interface is very useful for defining custom behaviour for looping over objects, however I just noticed that looping over such objects in Smarty will not work correctly.
Smarty will in fact cast an object back to an array, so when you loop over it, the template will loop over the object's properties (as opposed to using the rules defined by the Iterator methods).
For example, I used code similar to the following to create a class over which I can loop. This lets me loop over the protected $_data array.
<?php
class MyClass implements Iterator
{
protected $_data = array();
public function rewind()
{
reset($this->_data);
}
public function current()
{
return current($this->_data);
}
public function key()
{
return key($this->_data);
}
public function next()
{
return next($this->_data);
}
public function valid()
{
return $this->current() !== false;
}
public function size()
{
return count($this->_data);
}
}
?>
What I want to be able to do is loop over each element in the array with the following code:
{foreach from=$myClassObj item=row}
{$row}
{/foreach}
However, this will not work as expected in Smarty. To get around, I implemented as method called getData() which simply returned the array. This meant my template had to look as follows:
{foreach from=$myClassObj->getData() item=row}
{$row}
{/foreach}
It's a bit annoying to have to do this, since in some ways it defeats the purpose of the using the Iterator interface, but I guess sometimes small sacrifices need to be made.
PostgreSQL 8.3 was released yesterday, boasting a range of performance increases and new features.
One of the new features I found interesting was the bundled support of full text indexing, based on the popular tsearch2 module.
We will try to bring you some articles on PhpRiot in the near future on using these new features.
If you are interested in publishing your own PHP-related articles, we now have an article submission guide available for to you use as a starting point.
Visit the Write for PhpRiot page for more details.
It's been a while, but some new content has finally arrived on PhpRiot! Our first new article is entitled Monitoring File Uploads using Ajax and PHP.
We hope to add a lot of new content in the coming weeks and months as we strive the make this site one of the best PHP development sites on the web.
The owner of PhpRiot, Quentin Zervaas, has released his first PHP book, entitled Practical Web 2.0 Applications with PHP. This book walks the reader through creating a complete web application from start to finish.
More information about can be found on this web site at http://www.phpriot.com/books/isbn/1590599063.
The back cover of the book reads as follows:
Many programming books on the market today focus specifically on a particular methodology or software package, and although you will gain a solid understanding of the subject matter from these books, you won't always know how to apply what you've learned in a real-world situation. This book is designed to show you how to bring together many different ideas and features by starting with a clean slate and gradually building the code base so it evolves into a complete web application.
The premise of the application we build in this book is that it is a "Web 2.0" application. What this means is that (among other things) our application generates accessible and standards-compliant code while making heavy of use of Ajax. We achieve this by using the Smarty Template Engine and Cascading Style Sheets, as well as the Prototype JavaScript library. Additionally, we create a fun and intuitive interface by applying simple visual effects on various pages using the Scriptaculous JavaScript library.
To help with the development of the extensive PHP code in this book, we use the Zend Framework. This is an open source PHP 5 library that contains many different components that you can easily use in any of your day-to-day development. We use many of the Zend Framework components in this book, such as database abstraction (with a focus on MySQL and PostgreSQL), logging, authentication, and search.
The application we build in this book is a collaborative blogging tool. It will allow users to register and create a personal blog. When creating blog posts, users will be able upload images, apply tags, and assign locations (using Google Maps). We will also look at how to use microformats when displaying user blog posts.
Quentin Zervaas
Today PhpRiot has been relaunched with a brand new look and feel and some great new tools to help PHP programmers (both beginners and experienced users) learn more about PHP and other web development.
Although the site has had little new content in the past year, we are now committed to bringing you a whole new range of articles to keep up with current trends.
Additionally, the content from the old PhpRiot has been included here and will gradually be updated to reflect current trends and technology.
Please continue to submit your comments - we still have a backlog of older comments to approve but in the coming weeks these will be filtered, approved and formatted.
If you have any suggestions for the site or any articles you would like to see written, please feel free to contact us.
|
|