Short story: Rendering a view over ajax in Yii Framework might include JS and CSS files. There is no way for Yii to know that some of these files might already be present in your DOM. Having your browser re-download and add duplicates of these files can or will lead to problems. A short snipped of JS code will filter away all JS and CSS references from incoming content, while leaving inline script and style intact. No server-side changes required. Scroll down for code.

Longer story: If you attempt to render a view with processing of script in Yii Framework you’ll end up with script tags for whichever scripts the components in your view requires. For example, if you have a view which uses the CListView component, you’ll end up with jquery.listview and jquery.js. This is pretty much what you would expect when rendering a view, but it will lead to problems if you are rendering this in an ajax response and the scripts in question are present in the DOM. Yii has no way to know that you have already executed a request, which returned these scripts. There has been some talk on the Yii Framework forums on how to tackle this problem, but so far I’ve not seen any implementations or hacks that’s been satisfactory.

Server side tracking of client scripts
One way to go is to keep track of the script files that has been sent to the client on the server, and reset this state when a full page request is executed. This might seem like a good idea, but once a user starts browsing with several tabs at the same time it gets complicated. It will require hacks to prevent resetting in cases where requests fail midways etc. The state must be kept not only on a path basis, but also for submitted content (ie ajax post), which would further complicate things.

My proposal is to use jQuerys dataFilter hook (via $.ajaxSetup), which is invoked after ajax request and allows you to filter any data returned before it’s passed on to ordinary success-handlers etc.

Update: Thanks to NLAC for some code improvements.

Simply include this script after jQuery, or add this function to your existing code:

$.ajaxSetup({
	global: true,
	dataFilter: function(data,type){
		//  only 'text' and 'html' dataType should be filtered
		if (type && type != "html" && type != "text")
		{
            		return data;
		}
 
		var selector = 'script[src],link[rel="stylesheet"]';
 
      		// get loaded scripts from DOM the first time we execute.
        	if (!$._loadedScripts) {
			$._loadedScripts = {};
			$._dataHolder = $(document.createElement('div'));
 
            		var loadedScripts = $(document).find(selector);
 
			//fetching scripts from the DOM
		        for (var i = 0, len = loadedScripts.length; i < len; i++) 
			{
        		        $._loadedScripts[loadedScripts[i].src] = 1;
            		}
        	}
 
		//$._dataHolder.html(data) does not work
		$._dataHolder[0].innerHTML = data;
 
		// iterate over new scripts and remove if source is already in DOM:
		var incomingScripts = $($._dataHolder).find(selector);
		for (var i = 0, len = incomingScripts.length; i < len; i++)
		{
			if ($._loadedScripts[incomingScripts[i].src])
			{
	        	        $(incomingScripts[i]).remove();
            		}
            		else
            		{
                		$._loadedScripts[incomingScripts[i].src] = 1;
            		}
        	}
 
		return $._dataHolder[0].innerHTML;
	}
});

If you have improvements for this code, please email me at eirikhm@gmail.com

PHP 5 Social Networking cover

Contest is now over! Stay tuned for winners!

Want a chance to win the PHP 5 Social Networking book from Packt Publishing? Three copies are up for grabs in after a 14 day contest.

How to Enter

All you have to do is comment on why you’d like a copy of the book in the comments.  You can take a look at the book’s page at Packt for inspiration and additional information.

During, this contest, we’ll work with tokens. The more tokens you have, the greater your chance is of winning the a copy of the book. Leaving the answer in the comment field will provide you with one token, and tweeting about this giveaway will provide one. If you do both, we’ll give you not two, but three tokens. If you tweet about it, please link the tweet in the comment! My tweet is available here!

Deadline

The deadline for participating is March 10th, 2011. Any entries after that date will be discarded. Three winners will be picked at random, and announced shortly after the contest ends. Good luck!

Book review: PHP 5 Social Networking
ISBN: 1849512388
ISBN 13: 78-1-849512-38-1
Publisher:Packt Publishing
Author:Michael Peacock

PHP 5 Social Networking cover

Short story: If you are fresh to social networks, this book will get you up and moving. It explains how to build a fully featured social network, based on a custom underlying framework. At the end of the book you will have a functional site, and know the what’s what of social networks. It’s very easy to follow the author, and the code is very readable. New concepts and features are introduced in a way that makes it easy for the reader to keep up.


PS: Packt currently has a 40% off special offer on this book, so I recommend you pick it up via their website!


Slightly longer story: I must admit that I’m having problems seeing the value of rolling your own MVC framework when building applications like this. The main arguments made in favor of going custom is ease of maintenance, licensing and code efficiency. I really don’t buy these, as there are several good frameworks available under the BSD license, which are proven time upon time (Yii, Zend, Code Igniter, Symfony). Not only is the code maintained by teams of highly skilled developers, but also reviewed for security holes and exploits by the less good-mannered of our beloved internet. A *very* important aspect of social networking sites is security, and I feel that the book should spend more time on that subject (maybe including info on cross site scripting and related).
However, the one argument I really do see the value in is the process of learning. Writing a PHP framework is a very valuable exercise, and if you still have that on your TODO-list, this book should serve as a good guide on the way. The framework produced will allow you to keep extending and improving features after you are done with the material covered in the book.

Heads up! New book from Packt Publishing called PHP 5 Social Networking!

I just received a copy of PHP 5 Social Networking in eBook format, and plan on getting started reading it this week. The book looks really interesting, and closely matches my daily work as I’m now doing social networks on a full-time basis.

PHP 5 Social Networking cover
This book will demonstrate how to create, maintain, and extend a powerful social network site. It shows how to create your own flexible social networking framework, allowing users to sign up, customize their profile, befriend other users, share information, communicate, interact with one another, and much more.

You can check out the sample chapter Public and Private Messages right now.

Book review: Expert PHP 5 Tools
ISBN: 1847198384
ISBN 13: 978-1-847198-38-9
Publisher:Packt Publishing
Author:Dirk Merkel

Book cover: Expert PHP 5 Tools

Book cover: Expert PHP 5 Tools

Short version: If you are working with PHP you’ll want to read this book. Covering topics like continuous integration, documentation and unit testing thoroughly it gives an insight of great value to any PHP developer.

Slightly longer version: This book is aimed at developers already working with PHP on a daily basis, or developers which are picking up PHP. It’s main focus is the environment of the PHP developer. Areas like unit testing, continuous integration, application deployment, proper documentation and version control might already be very familiar if you have been working with PHP for a while, but this book covers each of these important areas in detail and with prime examples on do and dont’s. Even if you feel like you are doing quite well I’m sure this book will give you a few “aha!” moments. If you are coming from a hobby-background these areas might not be your strongest suit, and this book will help you get a firm grasp on what a professional PHP setup is all about. The chapter on continous integration is based around phpUnderControl, which is a nice piece of software for this purpouse. However, I would have liked to see other alternatives like for example Hudson. Luckily, moving over to a different CI app is fairly easy after having set up a phpUC installation with the phing/ant configuration.

The book is available both as paperback and eBook from Packt. I’ve been reading the eBook, which worked quite well for me. PS: Convering the PDF to ePub will destroy some of the formatting.

Check out the sample chapter Documentation with phpDocumentor

Book cover: Expert PHP 5 Tools

Book cover: Expert PHP 5 Tools

While I am currently reading PHP5 eCommerce Development I’ve also got lined up a copy of Expert PHP 5 Tools from Packt.

This book will enable you to take your PHP development skills to an enterprise level by teaching you the skills and tools necessary to write maintainable and efficient code. You will learn how to perform activities such as unit testing, enforcing coding standards, automating deployment, and interactive debugging using tools created for PHP developers – all the information in one place. Your code will be more maintainable, efficient, and self-documented.

Check out the sample chapter Documentation with phpDocumentor

I have been reviewing some books from  Packt Publishing lately, and I’m now expecting a copy of PHP 5 E-commerce Development in a few days.  I have been looking forward to for a while, as I will be working on a similar project in the near future. Here is the lowdown:

Php 5 eCommerce Development Book Cover

Php 5 eCommerce Development Book Cover

This book will show you how to create your own PHP framework that can be extended and used with ease, particularly for e-commerce sites. Using this framework you will be able to display and manage products, customize products, create wish-lists, make recommendations to customers based on previous purchases, send email notifications when certain products are in stock, rate the products online, and much more.

You can check out the sample chapter Enhancing the User Experience now.

Mastering phpMyAdmin 3.1 Cover

Mastering phpMyAdmin 3.1 Cover

Book review: Mastering phpMyAdmin 3.1
ISBN: 9871847197863
Publisher: Packt Publishing
Author: Marc Delisle

I had pretty much forgotten phpMyAdmin when I got a mail from Swati at Packt Publishing asking me to review this book. It’s been a very long time since I last used phpMyAdmin. When I first started out with web development (under Windows) and PHP I was hosted on a shared web host. They had phpMyAdmin installed as their main database management tool. With little to no knowledge on databases I was very happy to be able to do my basic list of operations to get stuff working. Needless to say I was a lightweight user.

Fast forward to today. I’ve moved on to Linux and the way of the command-line as many others, using the MySQL Gui Tools (Query Browser, Administrator) in addition. The tools from MySQL sure have their quirks and bugs, but they have mostly suited my needs for the last years. So, how does phpMyAdmin hold up, and is this the right book to get you started?

The book, written by Marc Delisle, clocks in at 326 pages, split into 18 chapters. The topics range from basic installation and database / table management to the “Multi-Table Query Generator” amd “The Relational System”.

The first few pages of the first chapter explains a bit background info on the software, which is pretty much skim-though-if-interested. More interesting, it covers installation for various platforms. The coverage on the installation parts can be a bit short for new users, but should be sufficient in most cases.

I especially liked chapters 2 and 3. Chapter 2 deals with authentication, which is pretty well covered, and the features are surprisingly extensive. Previously I was a bit reluctant to use phpMyAdmin in a production environment due to the lack of proper authentication, but these added features grants it a new evaluation. In chapter 3 the author spends time explaining the GUI itself and how it can be customized. Some parts of this section will definitely be interesting for people doing web hosting as it allows some branding of the software itself as well as laying down some ‘ground rules’ on the feature set to expose. In addition there are tips on user-centric adjustments for optimizing the work flow for the developer using the software. When using it on a regular basis this information is very nice to have.

Chapters 4 and 5 and 6 deals with database, table and data management. These chapters will probably be skim-trough material for most experienced developers, as the GUI is quite self-explanatory when it comes to these kind of actions. However, it’s worth mentioning that the author points out lots of configuration keys for controlling both the GUI, behavior and again features offered. Nothing is crucial for the lightweight user, but if phpMyAdmin is your main tool for the job you’d want to read these chapters in detail as well.

The coverage of exporting schemas and data is quite well done. Again I was surprised with the list of formats supported by phpMyAdmin. The author takes care to describe the various formats, as well as server-side requirements and how-to’s where applicable.

There is a chapter dedicated to searching, which I do not think needs a whole chapter on it’s own since it’s also very intuitive to use the GUI here. However, the chapter is quite short. The same goes for table and database operations which are also covered. Again I find the GUI clear enough for most of these tasks to be straight forward.

Chapter 11 deals with ‘The Relational System’, which I’ve never heard about. Turns out it’s pretty neat! The author does a good job of covering the tool and it’s features. It takes a bit of extra configuration to get it running (create the phpMyAdmin database). This is basically a tool that lets you work visually with your database, seeing relations between tables etc. I’ve mainly used MySQL Workbench when I’ve had to generate a model based on a database. This is a viable replacement. The chapter dealing with system documentation can come in handy if you like to document your schema.

There is also a chapter dedicated to MySql 5.0 and 5.1 features which may come in handy if you are up to date on that front.

Conclusion
I’ve learned that phpMyAdmin has evolved quite a bit, especially in terms of authentication features and installation scripts. I was quite happy to set up the config by hand, but I think the guided setup script is a quite nice feature to new developers. My impression of phpMyAdmin has definitely changed. I used to view it as a “hobby-developers-tool” for database access, but I’ve come to realize that it offers a wast selection of features that might reduce both time and complexity for database management. For shared web-hosting and development environments it’s a really nice tool to have.

The book does a very good job at documenting phpMyAdmin. Some parts of the application are really too basic to describe in detail in a book, however the author has tackled this nicely by adding references to configuration tweaks and settings which makes these chapters interesting to the more advanced users.If phpMyAdmin is your weapon of choice when it comes to database management you’d definitely want to read this book. If you want to take it for a spin first, check out this sample chapter.

I just finished the initial trial migration of a Discus v4.x based board over to vBulletin.

Now, I’d like to write a few words on Discus. I cannot see why anyone looking to set up a new board would choose this software. It’s actually file based (!). Yes, you heard me. The posts, users and threads are stored in (plain) text files. I was quite surprised the first time I got around to checking out what I was supposed to migrate. If you head over to their site and check out a demo-site or two you’ll notice that the whole board seems a bit … unprofessional. It currently sells for 149 USD, which is quite amazing when you can get vBulletin for 180USD, or even phpBB for free. I went with vBulletin because they supported (at least partial) import from Discus, as well as the email based service in case I got stuck.

Now, the data migration. Upon purchasing vBulletin I got a migration utility called ImpEx which supports quite a number of boards to import from. Discus is listed as a tier 3 board, meaning it’s not actively supported anymore.. not a good sign, but still worth a shot.

Here is a quick recap of the required actions:

1. Download vBulletin and ImpEx from vBulletin.com
2. Create a new database for vBulletin
3. Install vBulletin as described here.
4. Install the ImpEx tool as described here.
5. Configure ImpEx as described here.
6. Run the ImpEx tool for Discus

Now, in step 6 there are some modules to import. Some of them runs in a matter of seconds, while others takes up to 10 minutes in my case. I’m not sure if the script actually refreshes, so one might want to up maximum execution time for PHP to be safe.

To my surprise everything went absolutely fine. Not a single hickup in the migration scripts. After the data was imported I followed the post-migrate instructions and did some data verification. Everything seemed to be present, but I was not able to see any threads in the forums. I could find them with searching, and when I opened a thread it clearly stated that it was belonging in the correct forum. After looking around for some time I discovered that the forums from Discus was now configured to act as categories. I solved this by going to Edit Forum -> Act as Forum and set it to Yes for each forum. When I got back to the forum listing everything was in order.

The only things left is to move the forums around some, get a proper language pack and some other minor adjustments. All in I’m quite satisfied with the whole process. Kudos to vBulletin.

At no time is freedom of speech more precious than when a man hits his thumb with a hammer.

~Marshall Lumsden

This is an experiment in designing an internationalization feature which I’ve been thinking about for a while. The idea is for people to come up with designs and implementations for the described requirements, and get a healthy discussion going on how to get a feature like this implemented in the best way. I’ve came up with some features and requirements which should make the design somewhat interesting.

Wanna play? If so, continue reading.

Now, let’s consider a website, which is to be deployed for several markets (in several countries), and serve both residential and corporate customers.

Requirements

A “tag” is an identifier for any given text that may be translated. The “tag” can be the text itself in the source language, or an identifier such as LABEL_CLICK_HERE, all depending on the implementation.

A tag’s content can be translated to any given language

This is the most basic feature, and does not need any explanation.

Any given market should be able to use the application in any given language

Customers in the French market should be able to view the application in German and so on. Does not sound tricky, but see next point.

A tag’s content *may* have different meaning in different markets

For example, in the US a zipCode validation error will differ from the zipCode validation error used in Spain, but surname validation errors will be the same. This also goes for descriptive texts for features and services which might differ. However, for 90%+ of the translated texts, the English translation in Spain would be the same as the english translation in the US.

A tag’s content *may* differ based on the context of the user

Imagine the front-page when a used is logged in. A text is presented here with information about available features, instructions on how to use them etc. Now, some of these features are not available for residential customers, while some are exclusive to residential customers. The usage/instructions of the features may be different for corporate customers. In addition, both residential and corporate customers have roles in the application (admin users and regular users), and the content may differ based on the role. Most of the tags will just have one content, but some may have several. The available contexts could be visualized as a tree structure, with ‘ALL’ at the top, which forks out to corporate and residential, which in turn forks out to admin / user:

Contexts

Contexts

When retrieving content for a tag the system should first look for the user’s context, for example “Residential Admin”, and if no content is present it shall select the parent etc.

Any changes to a tags’s content should be kept in a history log

Every time a tag’s content is changed, the old version should be kept for historical purposes. A nice bonus would be to be able to change a tag’s content ahead of time , that is, setting an effective date.

These are the basic requirements I’ve made up for this experiment. Now, I’d like to hear how you tackle internationalization in your application, and how you would design a implementation which would sastisfy the requriements described here. I’m working on my own implementation for this which I’d like to share after I’ve seen what other people come up with. If you have suggestions for more requirements which would make this even more interesting, please send a comment!

[tags]PHP,Internationalization[/tags]