Let me introduce you “Type hinting”Type Hinting - PHP

Lets face it, PHP was thought and developed as a weakly typed programming language. But with more and more Object Oriented Approaches and structures introduced into PHP it needs to comply to certain rules. Those rules have been introduced in version 5 of PHP we have Type hinting which allows us to define the parameters’ type that a method or function expects which according to the documentation could be class or interface name, array or callable function or method.

How does it work?

Type hinting is quite straight forward approach. In the following example I’ll create a class that will use it:
[cc escaped=”true” lang=”php” line=”1″]class Product
private array $params;
private array $children;

public function __construct(array $params)
$this->params = $params;

public function addChildProduct(Product $product)
$this->children = $product;
In the example above we have two type hintings for the two methods we have defined, namely __construct & addChildProduct, this means that the code will expect corresponding variable types to be passed, e.g. “array” and object of type “Product”. If for some reason we pass different variable than expected the parser will throw a Fatal error similar to:
[cc escaped=”true” lang=”text”]”Catchable fatal error: Argument 1 passed to Product::__construct() must be an array, integer given, called in…”[/cc]
Many developers used to procedural programming or loose typed approach would complaint that this is unexpected and unwanted behaviour but in the world of Object Oriented applications this is important requirement for writing working, reliable and robust code that will provide necessary feedback at the entry point of a method opposed to an ambiguous error somewhere down in the code that would take time for debugging. The other solution  of the problem would be an IF-ELSE block to check for parameter type on every method which is first code duplication and second extra work for us and we are lazy, we don’t like extra work 🙂

Other benefits / IDEs

While type hinting is crucial for good code structure and compliments the contracts between the objects and their methods it provides another important benefit to the developers, code completion. IDEs like Eclipse and NetBeans are able to parse and index your code and libraries so when you start typing a class or method it gives you possible options that match the code you’ve written. Further more the IDE is capable of showing an error or warning if you’ve passed a mistaken parameter type.

This functionality could be extended even further with adding a phpDocumentator tag like so:
[cc escaped=”true” lang=”php”]/**
* Method documentation
* @param Product $product
* @return void
public function addChildProduct(Product $product)
$this->children = $product;
This comment will tell the IDE that our method expects an object of type Product and doesn’t return value. For our example code this doesn’t look as a significant feature but imagine that you work on a project with thousands lines of code finding such small tips in the code would almost impossible or at least very time consuming so leave the IDE to do its job and you could enjoy the coding.

Issues with scalar variables

Type hinting is great feature and in PHP that is even greater because it uses hybrid implementation, e.g. allows you to specify parameter type or leave it blank for any type. But there is a problem with the entire approach, scalar or primitive variables cannot be type hinted. Variables like int, string, float can’t be checked in the method declaration, you’ll get Fatal error. There are few proposal for solving this issue:

  • Strict type hinting
  • Unenforced type hinting
  • Casting weak type hinting
  • Strict weak type hinting
  • Boxing based type hinting

Those approaches are similar in some aspects but this is not a part of this post so if you’d like to see possible implementations and example functionality you can check this blog post which gives good insight for each of the approaches.

Tagged with: , ,

The problem

If you use MacOS and Chrome browser (recently this has been reported under other browsers and OS as well) you might have experienced an issue when downloading any Microsoft documents like Word, Excel, PoerPoint their file extension is automatically swapped to “.zip”. The reason for that are the server configurations and more specifically the MIME types of those files. Most browsers do not recognise the new “.docx”, “.xlsx”, “.pptx”. If you haven’t spotted that your users definitely have so it’d be good to test and apply that fix.


The solution

You can force the MIME type of those files in the .htaccess file which should be located in you public directory. To do so use the following code:
[cc escaped=”true” lang=”text”]AddType application/vnd.ms-word.document.macroEnabled.12 .docm
AddType application/vnd.openxmlformats-officedocument.wordprocessingml.document docx
AddType application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx
AddType application/vnd.ms-powerpoint.template.macroEnabled.12 potm
AddType application/vnd.openxmlformats-officedocument.presentationml.template potx
AddType application/vnd.ms-powerpoint.addin.macroEnabled.12 ppam
AddType application/vnd.ms-powerpoint.slideshow.macroEnabled.12 ppsm
AddType application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx
AddType application/vnd.ms-powerpoint.presentation.macroEnabled.12 pptm
AddType application/vnd.openxmlformats-officedocument.presentationml.presentation pptx
AddType application/vnd.ms-excel.addin.macroEnabled.12 xlam
AddType application/vnd.ms-excel.sheet.binary.macroEnabled.12 xlsb
AddType application/vnd.ms-excel.sheet.macroEnabled.12 xlsm
AddType application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx
AddType application/vnd.ms-excel.template.macroEnabled.12 xltm
AddType application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx[/cc]
Once you do that every time the server send a file to the user it will add the correct MIME type in the HTTP request and the file will be served and saved with ist original file extension.

Second fix

If you have a root access to your server you can add this fix directly to your “mime.types” file which should be located at: “/etc/mime.types”
[cc escaped=”true” lang=”text”]application/vnd.ms-word.document.macroEnabled.12 .docm
application/vnd.openxmlformats-officedocument.wordprocessingml.document docx
application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx
application/vnd.ms-powerpoint.template.macroEnabled.12 potm
application/vnd.openxmlformats-officedocument.presentationml.template potx
application/vnd.ms-powerpoint.addin.macroEnabled.12 ppam
application/vnd.ms-powerpoint.slideshow.macroEnabled.12 ppsm
application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx
application/vnd.ms-powerpoint.presentation.macroEnabled.12 pptm
application/vnd.openxmlformats-officedocument.presentationml.presentation pptx
application/vnd.ms-excel.addin.macroEnabled.12 xlam
application/vnd.ms-excel.sheet.binary.macroEnabled.12 xlsb
application/vnd.ms-excel.sheet.macroEnabled.12 xlsm
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx
application/vnd.ms-excel.template.macroEnabled.12 xltm
application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx[/cc]
For Apache 2.2 servers you might need to update the mime type configurations “conf/mime.types” as follows:

Old configurations
[cc escaped=”true” lang=”text”]application/msword doc dot
application/vnd.ms-excel xls xlm xla xlc xlt xlw
application/vnd.ms-powerpoint ppt pps pot potx sldx[/cc]
New configurations
[cc escaped=”true” lang=”text”]application/msword doc docx dot dotx
application/vnd.ms-excel xls xlsx xlm xla xlc xlt xltx xlw
application/vnd.ms-powerpoint ppt pptx pps ppsx pot potx potx sldx[/cc]

Tagged with: , , , , ,

Preventing web cache of XML file with htaccessI am having problems with a dynamically created images.xml being cached in internet explorer. The xml file is used by a flash slideshow player and for different pages on the site, has different images to show. IE isn’t reading the new images.xml each time.

I had a go at adding some cache control code to my .htaccess file but got an internal server error.


[cc escaped=”true” lang=”text”]RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|tinymce|flash|filemanager|sifr|scripts|ssi|slideshow|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

<FilesMatch “\.(xml)$”>
FileETag None
Header unset ETag
Header set Cache-Control “max-age=0, no-cache, no-store, must-revalidate”
Header set Pragma “no-cache”
Header set Expires “Wed, 11 Jan 1990 05:00:00 GMT”

Than I tried replacing this
RewriteCond $1 !^(index\.php|images|css|tinymce|flash|filemanager|sifr|scripts|ssi|slideshow| robots\.txt)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d


Add Cache-Control Headers

This goes in your root .htaccess file but if you have access to httpd.conf that is better.

This code uses the FilesMatch directive and the Header directive to add Cache-Control Headers to certain files.
[cc escaped=”true” lang=”text”]# 480 weeks
<FilesMatch “\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$”>
Header set Cache-Control “max-age=290000000, public”

# 2 DAYS
<FilesMatch “\.(xml|txt)$”>
Header set Cache-Control “max-age=172800, public, must-revalidate”

<FilesMatch “\.(html|htm)$”>
Header set Cache-Control “max-age=7200, must-revalidate”
If you are using far Future Expires Headers and Cache-Control (recommended), you can do this for these files.
[cc escaped=”true” lang=”text”]<FilesMatch “\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$”>
Header set Cache-Control “public”
Header set Expires “Thu, 15 Aug 2012 20:00:00 GMT”

Without Cache-Control Headers

No Cache-Control Headers

No Cache-Control Headers

With Cache-Control Headers

Cache-Control Headers On

Cache-Control Headers On

Currently AskApache.com Uses

You can use the HTTP Header Viewer Tool to check it.
[cc escaped=”true” lang=”text”]Header unset Pragma
FileETag None
Header unset ETag

# 1 YEAR
<FilesMatch “\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|mp3|mp4)$”>
Header set Cache-Control “public”
Header set Expires “Thu, 15 Aug 2012 20:00:00 GMT”
Header unset Last-Modified

<FilesMatch “\.(html|htm|xml|txt|xsl)$”>
Header set Cache-Control “max-age=7200, must-revalidate”

<FilesMatch “\.(js|css)$”>
Header set Cache-Control “public”
Header set Expires “Thu, 15 Apr 2010 20:00:00 GMT”
Header unset Last-Modified

Tagged with: , , , , , , , , , , , ,

Resizing an IFrame to fill in 100% height
Ever wonder how to create an iframe that fills the entire height (and width) of a page?

You probably tried writing something like:
[cc lang=”html” escaped=”true”]<iframe width=”100%” height=”100%”></iframe>[/cc]
and expected the iframe to fill up whatever it could.
The width=100% does what you expected and fills up the entire width of the page, but the height just stays about 200px.

The problem is that the IFrame is not a block element so its hight is fixed to about 200px unless you set the hight to exact size, e.g.: 550px but in most cases this won’t solve the problem I’ve described earlier.

There are many solutions of the problem some works well some don’t. For example there is a pure CSS solution that will fix it.

The solutions

 – CSS approach

You have to use the following style:
[cc lang=”css”]
html, body, iframe {
margin:0; /* remove any margins of the IFrame and the body tag */
height:100%; /* set height 100% so that it fills the entire view port*/
iframe {
display:block; /* force the iframe to display as block */
height:100%; /* assign 100% height */
width: 100%;
And here is the actual HTML:
[cc lang=”html”]

Demo: http://jsfiddle.net/dL8zj/

So this is great solution but it works only on full height page without any other elements. Let’s think of a page where we have header, main menu and footer and we want to stretch the IFrame within the content body of page and in this case we will need some JavaScript which will be run once the main page is loaded or resized:

 – JavaScript solution

Put this in the head of your page:
[cc lang=”javascript”]
function resize_iframe()
var height=window.innerWidth;//Firefox
if (document.body.clientHeight)
//resize the iframe according to the size of the
//window (all these should be on the same line)
parseInt(height – document.getElementById(“glu”).offsetTop-8)+”px”;

// this will resize the iframe every
// time you change the size of the window.
And inside your page’s body create the iframe tag:
[cc lang=”html”]


– JavaScript – second solution

Similar to the previous one there is another JavaScript function that can solve the problem:
[cc lang=”javascript”]function resizeIframe() {
var height = document.documentElement.clientHeight;
height -= document.getElementById(‘frame’).offsetTop;
height -= 20; /* whatever you set your body bottom margin/padding to be */
document.getElementById(‘frame’).style.height = height +”px”;
document.getElementById(‘frame’).onload = resizeIframe;
window.onresize = resizeIframe;


You’re more than welcome to share your thoughts on the previous solutions. If you stumbled on another one that hasn’t been mentioned here I’d like to see it and implement it in real world scenario so feel free to post a comment.

Tagged with: , , ,

HTML5 pushState - change page and URL attributeNowadays JavaScript and more particularly AJAX is used in every type of web applications. The asynchronous data loading is great asset of AJAX but it has one drawback, the user can’t use back/forward buttons of the browser to navigate through different states of the page that has been updated through asynchronous methods.


Web page Hash

There’s been a solution to the problem, not very elegant, but good for workaround. Many people and developers used to use the hash key to enable users to use the browser navigation buttons. One of the big players on the web scene, Facebook and Twitter, use this approach as well. The following links show how they have implemented it:



What is specific in the following examples is that they use hash key in the URL but also they have a separator: “!” this one makes sure that the following data has to be parsed in their application. You could use something like: explode(‘/’, $hash); to het all parts of the URL. In same time each different hash provides different URL for the browser and enables the navigation buttons so the user can go back and forth in the browser history. For jQuery there is a plugin thet enables you to use the hash and the browser history:

But now with HTML5 raise we have new option and solution for the former problem. HTML5 and in particular W3C has announced new document features and methods: jQuery History Plugin. Also there is pretty simple implementation of this functionality:
[cc escaped=”true” lang=”javascript”]$(function(){
// Initialize Tabs
if(document.location.hash!=”) {
//get the index from URL
tabSelect = document.location.hash.substr(1,document.location.hash.length);

HTML5 pushState



With these two options web developers can change the state of the page on-the-fly based on any event that occures on the page that the user is browsing. You can change the page title, URL and the state object which can be serialized and save on the client computer.
[cc escaped=”true” lang=”javascript”>$(“.link”).click(function() {
var stateObj = { test: “1” };
history.pushState(stateObj, “Tab 2”, “tab2.html”);
The former code will update the page URL the title will be changed to “Tab 2” and the state object parameter “test” will be set to 1. Thus if you have a image slider or tabbed content every time the user click on any of the tabs you can update the document state.
[cc escaped=”true” lang=”text”]http://yysource.com/tab1.html
The only problem is that the pushState is not supported by all browsers. At the time of writing the latest versions of Chrome and Firefox supported this functionality hopefully sooner than later will see all browser supporting HTML5 and will be able to use its full power and features.

Further reading


Tagged with: , , , ,

CSS - Debug nested elements in HTML layoutSometimes document structure and layout could be very difficult and complex. To achieve some goals designers tend to use a lot of nested elements in their code and after that style them with CSS. What if you want to see all this elements and how they are located and related to each other. There is one really fast solution to this problem through use of a couple lines of CSS:
[cc escaped=”true” lang=”css”]* { outline: 2px dotted red }
* * { outline: 2px dotted green }
* * * { outline: 2px dotted orange }
* * * * { outline: 2px dotted blue }
* * * * * { outline: 1px solid red }
* * * * * * { outline: 1px solid green }
* * * * * * * { outline: 1px solid orange }
* * * * * * * * { outline: 1px solid blue }[/cc]
All this code does is to highlight all elements and their nested elements. This will work up to 8 levels of nested elements in the HTML layout. If you want to distinguish more just add an extra row with extra asterisk.

More professional approach

You can achieve the same result with more professional approach by using add-on for your browser. For example in Firefox you can use the very popular Web Developer add-on. It has many useful functions that will help you in your daily routine but in our case we will use just 2 of them:

– Display Div order
– Display Element information

The first function is accessible through the toolbar, click on “Information -> Display Div Order” this will highlight all DIV elements in current document within all level. The only demerit is that all elements are with same border colour (red) and only DIV tags are shown.

The second option will highlight all elements and will provide even extra information for each of them like class, id, width, height, parent, ancestors and etc. This option is accessible through the toolbar “Information -> Display Element Information“. This is also accessible through short cut key combination: “Ctr + Shift + F“. This should bring an information window in the right hand side and will change the cursor allowing you to select element from current page. Upon selection the information window will display detailed data for the selected element. Play around with this function I am sure it help you a lot in your daily tasks.

If you have other ideas for layout and CSS debugging don’t hesitate to write them in the comments area below.

Tagged with: , , , , ,

CSS3 rotate transformI see many people are playing around the net with the new CSS3 features. The biggest problem is that some features are still not very well or at all adopted by some browsers. Since Microsoft had officially announced the IE6 countdown and it’s forthcoming death, designer and developers worldwide can relieve. But anyway in the following small tip I’ll show you how to rotate text or element in all browsers including your “beloved” IE6 🙂 We will use the transform property of CSS3 and for value we add “rotate” with required degrees.

For IE we can use a “filter” property with “BasicImage” value. It receives 4 parameters: 0, 1, 2, 3 which will rotate our element accordingly to 0, 90, 180, 270 degrees.

The code will work in Firefox, Opera, Chrome, Safari, IE6-9 and shouldn’t have any problems with mobile devices but hasn’t been tested.

Here is the CSS style to rotate a div element:
[cc escaped=”true” lang=”css”]div {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
transform: rotate(90deg);


Rotate me!
Tagged with: ,

First element of an array - JavascriptWorking with arrays is very beneficial for every developer in every language. But in different languages some operations are done differently. Very good example is retrieving first key from an associative array in JavaScript. In PHP you could use “foreach“, “list“, “array_pop“, “array_slice“, etc. But in JavaScript we don’t have all that functions so we have to stick to what the language offers us. Here is the actual tip:
[cc escaped=”true” lang=”javascript”]function getFirstKey( data ) {
for (elem in data )
return elem;

var myArray = {a: 1, b: 2, c: 3, d: 4};
// This will give us “a”
var firstKey = getFirstKey(myArray);
// This will give us “1”
var firstValue = myArray[firstKey];

Tagged with: , , ,

Joomla Radio Group - JHTMLJoomla provides very useful class called JHTML that can be used to produce different HTML elements saving us time and code. The Joomla team has provided a very useful class loader method “_()” in which we can pass string for an element we would like to generate. Example of elements are:

  • select.option
  • select.genericlist
  • select.option
  • select.optgroup
  • select.integerlist
  • select.radiolist
  • select.booleanlist
  • email.cloak
  • form.token
  • grid.published
  • grid.state
  • grid.order
  • grid.checkedOut
  • grid.access
  • grid.id
  • grid.sort

That is not the full extended list of options but that will give you a good idea of what JHTML could do for you. For now we will focus on the “select.option” and “select.radiolist” elements. Lets see it in action:
[cc lang=”php”]$option[] = JHTML::_( ‘select.option’, ‘left’, ‘Left’ );
$option[] = JHTML::_( ‘select.option’, ‘right’, ‘Right’ );

$select JHTML::_(‘select.radiolist’, $option, ‘align’, ‘class=”inputbox” ‘, ‘value’, ‘text’, ‘left’, ‘align’ );
echo $select
Here you can see very simple but exhaustive example of how to generate radio list. First we create an array of objects with type “select.option”. The method receives three parameters. First is pair of class and method that has to be loaded in our case this is class “select” which is translated to “JHTMLSelect” by the underlying code and invokes its method “option”. Following are two parameters that will be used by our element. First is value and the second is label. These two are completely up to you. Once we have our array with elements we can pass it to same method but with class loading string “select.radiolist”. This will generate our <select> HTML code and pass it to a variable in plain format. The difference here is that we have more parameters passed to the method.  First is the class and method to be loaded. Second is our array with options.  The third is the select “name” attribute in our case “align”. Forth parameter could be either string or an array of different HTML attribute to be used in our select. If it is array you can pass in it key, value pairs for class, id, JavaScript events or any other attributes you’d like to attach to the select tag. Next parameter is “value”  it specifies under which key is our value in the options array. By default that is “value” you can pass the default or just null. That is handy if you are using different array which for example holds the values under “data” key. Passing it as a key will help the script to find the correct value for each option. The next parameter is almost the same as key except it defines the text to be shown in the select’s options. Next parameter specifies which option or radio button is selected by default, in our case this is “left” also you could pass a variable or array of selected options. Finally we have an id argument if it’s empty the name will be used for id of the select.

This class is very useful especially if you have to create Yes/No radio buttons or group of buttons in the View of the website. This example is valid for Joomla v1.5 in v1.6 there has been some changes which will be covered shortly.

Useful links

Documentation for JHTML::_(‘grid.id’)
Joomla! 1.5 Country Select Box
JHtml Class Reference

Tagged with: , , , ,

If you have a website for sure you have come to the point wondering how to redirect all visitors to the WWW part of the domain. This is small tip explaining in details the actual .htaccess redirect. Enough talking let’s see some code:




[cc escaped=”true” lang=”text”]Options +FollowSymlinks
RewriteEngine on
RewriteCond %{http_host} ^domain.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,NC][/cc]

More details

FollowSymlinks – this option tells the server to follow Symbolic links. This are aliases or short cuts of existing files and/or directories on your server. By default this option should be enabled and you could skip this row but to prevent any 500 errors you’d better use it.

RewriteEngine on – turns on the actual URL rewriting engine that will fetch the request URL and change it according the following rules and conditions in the file.

RewriteCond  – This is back reference to  that will match our hostname/domain and if it starts with “domain.com” and it’s not a sub domain like “test.domain.com”, next row RewriteRule will be executed. Maybe you have spotted the flag at the end [NC] – it means no case, more thoroughly, our domain is matched in case insensitive way so “domain.com” and “DomAiN.com” are the same thing.

RewriteRule – That is the actual place where the magic happens. This command specifies a rule that will be executed upon request. It receives two parameters. The first one is a regular expression which fetch entire URL and replace it with the second parameter “http://www.domain.com/$1”. The number one tells the server that all following data after the main URL should be appended to the end of our new domain. This is taken from brackets in the first variable. You can reference as many parts as you want. Fast example is ([0-1]+)/([a-z]+) and $1 will contain all numbers and $2 will contain one or many characters. The flag at the end [R=301] defines a redirect also known as “Moved permanently” which will preserve your SEO ranking and will prevent search engines penalties.

Meta redirect/refresh

To do a server redirect you should have access to the server and you should have permission to create .htaccess file which is not always the case. In such situation you still can redirect your page by using meta tag called refresh.
[cc escaped=”true” lang=”html”]<meta http-equiv=”refresh” content=”2;url=www.yysource.com”/>[/cc]
You have to place this tag in the head of your page. The most important part is the content parameter. First thing, the number defines how long to wait before redirect the user. In our case 2 seconds followed by semi column and the link of the page we want to redirect.

JavaScript redirect

And finally we can use JavaScript but this is not the best approach considering some users may have disabled their JavaScript support in their browsers or the website is visited by search engine bot, they don’t have JavaScript so apparently won’t be redirected and may see wrong page or index wrong content. Anyway the JavaScript redirect is done as follows:
[cc escaped=”true” lang=”javascript”]<script type=”text/javascript”>
window.location = “http://www.google.com/”

Tagged with: , , , , ,