Thursday, May 29, 2008

[[ Model View Controller ]]

Model View Controller MVC is a time tested method of separating the user interface of an application from its Domain Logic.

Domain Logic: Sometimes called business logic. Domain Logic represents the calculations and data storage that form the core of the application. These are the reason for the applications existence.

The primary goal of MVC is to isolate UI changes and prevent them from requiring changes to the Domain Logic of the application.

The primary reason for this division is that the user interface and Domain Logic have different drivers for change and different rates of change. By making this separation, you can change the UI without touching the Domain Logic and vice versa.
MVC is sometimes confused with other patterns that have the same goal of separating user interface from Domain Logic, such as Presentation Abstraction Control.

Presentation Abstraction Control:
A pattern for implementing user interfaces, based around the concept of a heirachy of cooperating agents.

MVC divides an application into three concerns:


• Model - Encapsulates core application data and functionality Domain Logic.
• View - obtains data from the model and presents it to the user.
• Controller - receives and translates input to requests on the model or the view.

The separation into three concerns is inspired by a information processing model where the controller represents system input, the model represents processing and the view represents the output of the system.

Model


The model encapsulates the functional core of an application, its Domain Logic. The goal of MVC is to make the model independent of the view and controller which together form the user interface of the application. An object may act as the model for more than one MVC triad at a time.

Since the model must be independent, it cannot refer to either the view or controller portions of the application. The model may not hold direct instance variables that refer to the view or the controller. It passively supplies its services and data to the other layers of the application.

See Domain Model and Transaction Script to organize Domain Logic.

Passive Model

With a passive model, the objects used in the model are completely unaware of being used in the MVC triad. The controller notifies the view when it executes an operation on the model that will require the view to be updated.

The passive model is commonly used in web MVC. The strict request/response cycle of HTTP does not require the immediacy of an active model. The view is always completely re-rendered on every cycle, regardless of changes. This may be especially true in PHP where no state is retained between requests.

Active Model

In the active model, model classes define a change notification mechanism, typically using the Observer pattern. This allows unrelated view and controller components to be notified when the model has changed. Because these components register themselves with the model and the model has no knowledge of any specific view or controller, this does not break the independence of the model.

This notification mechanism is what provides the immediate updating that is the hallmark of a MVC GUI application.


Presentation Model

The purpose of MVC is to separate UI from domain logic. In doing so, an MVC implementation typically develops a set of reusable classes for each of the concerns in the triad. Sometimes, data or behavior that firmly belongs on the user interface side of the division can conveniently be represented using the infrastructure of the model side of the division. Thus objects that would appear at first glance to be in the model are really part of the interface concern, that is the view and controller.
Some examples include scrollbar positions and column sorting.

This is sometimes called an Application Model and the pattern known as MMVC after the idea that there are two separate models.

View

The view obtains data from the model and presents it to the user. The view represents the output of the application.

The view generally have free access to the model, but should not change the state of the model. Views are read only representations of the state of the model. The view reads data from the model using query methods provided by the model.

With an Active model, the view can register itself to receive notifications when the model changes, and the view can then present a more up to date version of the model.
Sometimes generic reusable view components can be arbitrarily connected to the model in a process known as binding.

See Template View and Transform View for strategies of implementing views.

Template View: A template is a document typically HTML with embedded markers which are replaced, manipulated, or evaluated via a template engine API to produce an output document.

Transform View:
A view that processes domain data element by element and transforms it into HTML.

Controller

The controller receives and translates input to requests on the model or view.
The controllers are typically responsible for calling methods on the model that change the state of the model. In an active model, this state change is then reflected in the view via the change propagation mechanism. In the passive model, the controller is responsible for telling the view when to update.

In MVC, The controller is NOT a Mediator between the view and the model. The controller does not sit in between the model and the view. Both the controller and the view have equal opportunity to access the model. The controller does not copy data values from the model to the view, although it may place values in the model and tell the view that the model has changed. see Presentation Abstraction Control where the control layer acts as a mediator between Presentation and Abstraction.

The word controller is overloaded with different meanings in various patterns. see what is a Controller Anyway There are several of these controller patterns: Front Controller A single point of dispatch for incoming http requests. Page Controller Controls the flow of logic of a single web page. Application Controller Controls the flow of logic of a single application.

Front Controller:
A front controller presents a single point for a web server to interface with a web application.

Page Controller:
A Page Controller is one object or file declaration designed to handle the request for one logical web page or action.

Application Controller: A centralized point for handling screen navigation and the flow of an application.

Because the popular MVC framework Java Struts from a PHP Perspective implements a combined Front Controller and Application Controller, some people assume that this is what is meant by the MVC pattern in the context of a web application. For the same reason, many descriptions of the Front Controller pattern on the web do not draw the distinction between a Front Controller and a Application Controller.

Relationships between components


View Controller Relationship


In traditional smalltalk MVC, views and controllers are tightly coupled. Each view instance is associated with a single unique controller instance and vise versa. The controller is considered a Strategy that the view uses for input. The view is also responsible for creating new views and controllers.

It is logical that views and controllers are strongly related, the input and output of an application is strongly related. In most GUI MVC frameworks, the view and controller are simply merged into one object. This is called Document View. The view and controller are combined as the view. The model becomes known as a document.
A passive model shifts more responsibility into the controller, as it must notify the views when they should update.

The modern web usage of MVC shifts even more of the traditional responsibilities of the view to the controller. The controller becomes responsible for creating and selecting views and the view tends to lose responsibility for its controller.
Sometimes responsibility for creating and selecting views is delegated to a specific object, this is known as the Application Controller pattern for web MVC and View Handler for GUI MVC.

The rigid request/response cycle of HTTP may make the Document View variant less popular in web applications than in GUI applications although the controller is still strongly related to the view. The HTTP request is handled by the controller, the processing to the model, and the response is handled by the view.

Model View Relationship

The view depends on the model. Changes to the model interface require parallel changes in the view.

It is very difficult to achieve a strict separation between the model and view. For example, consider the requirement “Show negative balances in red.” At first glance, this appears to be strictly an output requirement and a test might be placed into the view in roughly this form:

if balance < 0 then red

This would violate the separation of concerns in MVC. Upon further analysis it turns out that the real requirement is “show overdrawn balances in red” and the definition of overdrawn =balance < 0= should be placed in the model as that is domain specific. It is very easy for domain logic to migrate out of the model and into the view. Template View contains further discussion of this issue.

Model Controller Relationship

The Controller depends on the model. Changes to the model interface may require parallel changes to the controller.


Benefits of MVC


Substitutable user interface


Different views and controllers can be substituted to provide alternate user interfaces for the same model. For example, the same model data can be displayed as a bar graph, or a pie chart, or a spreadsheet.

Some examples: Read only UI Expert and novice specific UI Different human languages Alternate input mechanisms User specific themes Alternate output formats XML, HTML, etc Alternate form mechanisms HTML forms, XForms, PDF forms

User interface components


Because MVC demands that the user interface of an application be structured into a hierarchy of objects and defines a standard relationship between these objects, generic versions of these objects are possible. They are usually called user interface components and no modern GUI environment is without a full complement of them usually combining view and controller into a single object. WACT is an attempt to provide a similarly rich set of components for web development that maintain the separation between view and controller. components promote reuse and reduce the need for special subclasses. These are known as “pluggable views” in the smalltalk MVC literature.

Multiple simultaneous views of the same model

Multiple different views can be active at the same time. Each view simultaneously and independently presents the same information from the model. This applies more to GUI MVC than web MVC.

Syncronized views


The change propagation mechanism insures that all views simultaneously reflect the current state of the model.

Easier user interface changes


Changes affecting just the user interface of the application logic become easier to make.

Easier testing

With MVC it can be easier to test the core of the application, as encapsulated by the model.

Drawbacks of MVC


Increased complexity


If reading this page doesn’t convince of you the complexity of this pattern, consider all of the auxiliary patterns that co-occur with MVC.

Close coupling of views and controllers to model

Changes to the model interface require parallel changes in the view and may require additional changes to the controller. certain code changes become more difficult.

Potential for excessive updates

The change propagation mechanism can be inefficient when frequent model changes require many change notifications. This is generally not as much of a problem if a passive model is used.

Close coupling between view and controller
strict separation is difficult if not impossible.

Saturday, May 24, 2008

Date format validation in PHP

Validate the date which is entered from textbox in “YYYY-MM-DD” format. Well, we can validate the format of the date using regular expression but how to validate weather that date is valid date or not, such as “2007-02-29″ is the correct format of the date but it’s not the valid date.
To overcome that situation, I’ve used checkdate() function available in PHP for validation of date.

Function to validate date format in PHP
function checkDateFormat($date)
{
//match the format of the date
if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/”, $date, $parts))
{
//check weather the date is valid of not
if(checkdate($parts[2],$parts[3],$parts[1]))
return true;
else
return false;
}
else
return false;
}


In the above function, first of all format of date is validated using regular expression. As you can see the in the preg_match() function, there are three expression each separated by “-” and there can be only digits of length of 4,2 and 2 in these expressions. If the date format is incorrect then this function returns “false” value. And, if the supplied string contains the valid date format then the part matching each expression are stored in the “$parts” array. Such as, if we supply “2007-03-12″ then “2007″, “03″ and “12″ are stored in the “$parts” array. After that, checkdate() function of PHP is used check weather the supplied date is valid date or not.

Example


echo checkDateFormat("2008-02-29"); //return true
echo checkDateFormat("2007-02-29"); //return false

Server variables available in PHP

You guys must have know about server variables in PHP. Server Variables are those variables which are inside the super global array named $_SERVER available in PHP. There are many server variables in PHP and some of them are very useful for fore developing PHP projects. I’m going to post here some of the very useful server variables available in PHP development.

8 Useful server variables available in PHP

1) $_SERVER['REQUEST_URI'] - It return the URL in to access the page which is executing the script. If you need to type http://www.example.com/product.php?id=5 to access the page then $_SERVER['REQUEST_URI'] returns “/product.php?id=5″.

2)$_SERVER['DOCUMENT_ROOT'] - Returns the root directory of the server which is specified in the configuration file of server. This variable usually returns the path like “/usr/yoursite/www” in Linux and “D:/xamps/xampp/htdocs” in windows.

3) $_SERVER['HTTP_HOST'] - Returns the host’s name as found in the http header. This variable usually returns the path like “example.com” when the you find “http://example.com” in browser’s address-bar and return “www.example.com” when you see http://www.example.com in the address-bar. This is quite useful when you’ve to preserve session while making online payment using PHP since session stored for “http://example.com” is not same as for the “http://www.example.com”.

4) $_SERVER['HTTP_USER_AGENT'] - Returns the user agent’s (browser) detail accessing the web page. We can use strpos($_SERVER["HTTP_USER_AGENT"],”MSIE”) to detect Microsoft Internet explorer or you can use strpos($_SERVER["HTTP_USER_AGENT"],”Firefox”) to detect firefox browser in PHP.

5) $_SERVER['PHP_SELF'] - Returns the file-name of the currently executing script. Let’s suppose that you’re accessing the URL http://www.example.com/product.php?id=5 then $_SERVER['PHP_SELF'] returns “/product.php” in your script.

6) $_SERVER['QUERY_STRING'] - Returns the query string if query string is used to access the script currently executing. Query strings are those string which is available after “?” sign.if you use $_SERVER['QUERY_STRING'] in the script executing the following URL “http://www.example.com/index.php?id=5&page=product” then it returns “id=5&page=product” in your script.


7) $_SERVER['REMOTE_ADDR']
- Returns the IP address of remote machine accessing the current page. But you can’t relie on $_SERVER['REMOTE_ADDR'] to get the real IP address of client’s machine. See this article to know how to get real IP addrees in PHP.

8 ) $_SERVER['SCRIPT_FILENAME']
- Returns the absolute path of the file which is currently executing. It returns path like “var/example.com/www/product.php” in Linux and path like “D:/xampp/xampp/htdocs/test/example.php” in windows.

Hide .php extension with url rewriting using .htaccess

hiding php file extension
Do you want to hide your web site’s server script identity? if you don’t want to reveal the programming language (server side script) of your website to visitors of website so that any hacker or spammer will not be able to intrude or inject any code in your website.

Here is a small technique for you, you can use .html or .asp file to work as a php file i.e. use .asp or .html extension instead of .php. You just need to create a .htaccess file and put the following code in the .htaccess file. Remember that the .htaccess file should be placed in the root folder of your website.


# Make PHP code look like asp or perl code
AddType application/x-httpd-php .asp .pl


if you place the the above code in the .htaccess file then you can use contact.asp as the name of the file. Now a visitor thought that it is a ASP file but this file contains the codes of PHP.

You can put the following code in .htaccess file to work .htm or .html file as PHP file.

# Make all PHP code look like HTML
AddType application/x-httpd-php .htm .html


But there was one flaw in that technique you have had to change the file extension explicitly but in this post I’m going to show you how to rewrite the URL instead of renaming the file extension Using this technique you will see product.html in the address bar of the browser but the actual file name remains product.php and you don’t need to rename the file extension. Furthermore you can rewrite the URL like product.php?id=5 to product-5.html.

what is the benefits of rewriting URL?

When a search engine visits the dynamic url like product.php?id=5 it does not give much importance to that URL as search engine sees “?” sign treat it as a url which keeps on changing. so we’re converting the dynamic URL like the product.php?id=5 to static url format like product-5.html. We’ll rewrite the url in such a way that in browser’s address bar it will display as a product-5.html but it actually calls the file product.php?id=5. So that why these kind of URL also named as SEO friendly URL.

what is required for URL rewriting ?

To rewrite the URL you must have the mod_rewrite module must be loaded in apache server. And furthermore, FollowSymLinks options also need to be enabled otherwise you may encounter 500 Internal Sever Error. If you don’t know much about mod_rewrite module then please check this post to know how to check and enable mod_rewrite module in apache?

Examples of url rewriting for seo friendly URL


For rewriting the URL, you should create a .htaccess file in the root folder of your web directory. And have to put the following codes as your requirement.

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ $1.php [nc]


The following example will rewrite the test.php to test.html i.e when a URL like http://localhost/test.htm is called in address bar it calls the file test.php. As you can see the regular expression in first part of the RewriteRule command and $1 represents the first regular expression of the part of the RewriteRule and [nc] means not case sensitive.

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ products.php?id=$1


The following example will rewrite the product.php?id=5 to porduct-5.html i.e when a URL like http://localhost/product-5.html calls product.php?id=5 automatically.

Tuesday, May 20, 2008

Open Source Shopping Cart

Ecommerce Web Design: 20 Open Source Shopping Cart Solutions

Let’s face it: Owning a website for your business is pretty much a requirement in this day and age. What good is a website that only shows customers what your company sells? Why not actually sell to them while they are there?
Use any of these 20 open source shopping carts to maximize your sales potential. Some of these aren’t open source, but they are all free. Create an online store and increase your revenue.
1. WP e-Commerce at Instinct Entertainment
WP e-Commerce is a very powerful e-commerce cart for WordPress. It uses your WordPress database to keep track of customers. You can do pretty much anything you can with other carts, while integrating with WordPress.
2. CubeCart
This shopping cart is very popular. It’s entirely free for version 3, with the exception that you leave their copyright notice in your footer. CubeCart has a large amount of payment gateways (Google Checkout, Paypal) and a very active community. Their support forums are lively and many people contribute plugins to the cart. Version 4 is pay-only, but has SEO out of the box.
3. Magento
Magento is currently in beta (it’s only up to version 0.6!) but is already shaping up to be one of the best e-commerce carts out there. Magento features clean urls and SEO from the start. Everything is designed in a clean and simple way. The code it outputs is semantic, which is very rare for e-commerce carts, even commercial ones.
4. osCommerce Online Merchant
osCommerce is a very popular online shopping cart. osCommerce supports multiple currencies, allows customers to print invoices from the order screen, and has an easy database backup system. Transactions are also carried out in SSL, making them more secure.
5. osCMax
osCMax is a branch of osCommerce. It gives you unlimited products and categories, multiple payment gateways, multiple shipping gateways and separate customer groups. Because osCMax is so similar to osCommerce, you can use many of the plugins that were made for osCommerce inside osCMax.
6. OpenCart
OpenCart feels lightweight but is full of great features. The backend is very simple to use. On really great feature is that customers can write their own reviews of the products listed. The latest version has also moved towards xhtml/css for the frontend.
7. Zen Cart

Zen Cart has been around for a while and recently moved to xhtml for templates. Zen Cart also supports multiple payment and shipping options, quantity discounts and coupons. The support forums are very active and most people on them are friendly and helpful. The newest version has added support for PayPal Express Checkout.
8. cpCommerce
cpCommerce is an easy to customize shopping cart. It’s template based so you never have to edit more than 5 files to change its look. You can view your store’s history, specify manufacturers and hold sales.
9. Digistore Free Ecommerce
Do you like a lot of options with your ecommerce carts? Good, because Digistore allows you to run your store in SSL, have express checkout, let guests check out without registering and more. Digistore supports Authorize.net and PayPal for checkout.
10. VirtueMart
VirtueMart is a free ecommerce web design plugin for both Joomla and Mambo. It can be used to display a catalog, or can be used as a full fledged shopping cart. You can assign products to multiple categories, sell downloadable goods and notify customers when an out of stock item is back in stock.
11. Boss Cart
Boss Cart is a fairly new shopping cart. It has support for PayPal gateways, it’s template driven, it has search engine friendly pages and is easy to set up. You can even embed flash movies in product pages. Work on version 2.0 has recently started too.
12. PHP Shop
PHP Shop is an ecommerce cart built on PHP. It uses CSS-based themes so it is very easy to customize. The product descriptions are edited with a WYSIWYG editor. PHP Shop supports SSL and can process credit cards live, depending on the payment gateway.
13. PayPal Shopping Cart
Did you know that PayPal offers a shopping cart that can be integrated with your current site? There is no cost for setting this up and it allows you to process credit cards and bank account payments immediately.
14. BakeSale - Simply Shopping Cart
BakeSale is quite a unique shopping cart. It is a “no-frills-get-only-what-you-need-and-nothing-more” cart. There are no ratings for products and no customer reviews. This also means that there is not bloat. You use the cart for one purpose only, to sell your products to a person who wants to buy them.
15. Mal’s e-commerce
This is a full featured ecommerce shopping cart completely free of charge. The only thing not included is credit card processing. Credit cards must be processed manually or you can buy a third-party payment gateway. It does support PayPal however.
16. Ubercart
Ubercart is a full featured ecommerce cart add-on for Drupal. It features single page checkout, anonymous checkout and integrated payment systems for multiple payment gateways. Ubercart is PayPal certified.
17. Fat Free Cart
Fat Free Cart is the simplest shopping cart I have ever seen. All you do is copy and paste some code and viola! You have a store on your website. Checking out is handled by either Paypal or Google Checkout. You do not have to sign up for this code, you simply copy and paste it.
18. AgoraCart
AgoraCart is a very popular online shopping cart. It features a css manager so you can edit the look of your cart online, unlimited product options, up to 4 different tax zones at the same time, lots of shipping options and tons of payment gateways. AgoraCart gives you many options for your store.
19. Cart97
Cart97 has a lot of great features. It’s easy to set up and very, very easy to run. Customers can submit reviews, when viewing item details it suggests other items for sale, it supports wishlists and even has sale options. The item detail pages work similar to Amazon so customers feel comfortable shopping. The only downside is that it isn’t the easiest cart to customize.
20. storesprite
storesprite’s motto is “free certainly does not mean basic”. Their cart has many features including automatic tax calculation, automatic delivery cost calculations, customer ratings and reviews and featured products. That backend panel is designed to be easy to use, even for someone who has never worked with ecommerce before.

What is Joomla

Joomla is a free, award-winning content management system written in PHP which allows users to easily publish their content on the world wide web and intranets. Joomla is created as an open-source project where individuals and teams contribute their skills to its development as well as its supporting systems.
While Joomla is packed with features, its greatest quality is that it is extremely extensible. Because of its extensible structure, there aren't many things you cannot do with Joomla. A short list of some important features of Joomla are the following:
• Page Caching
• Web Indexing
• RSS Feeds
• Printable Page Versions
• Newsflashes
• Blogs
• Forums
• Polls
• Calendars
• Website Searching
• Language Internationalization

Making website management simple.


The basic Joomla! package is designed to be easy to install, even for non-programmers. Most people have no trouble getting the software running, and there is plenty of support available for newbies. We have a growing, active community including 1,000s of friendly users and developers eager to help and learn from each other.
One of the best things about Joomla! is how easy it makes adding or editing content, updating images and multimedia, and managing critical data that makes your company or organization operate. Anybody with basic word processing skills can easily learn to manage a Joomla! site! Via a simple, browser-based interface you will be able to easily add new press releases or news items, manage staff pages, job listings, product images, and create an unlimited amount of sections or content pages on your site.
For many people, the true power of Joomla! lies in the application framework that makes it possible for thousands of developers around the world to create powerful add-ons and extensions to this robust content management system. Here are just some examples of the hundreds of available extensions:
• Dynamic form builders
• Business/organizational directories
• Document management
• Image and multimedia galleries
• E-commerce and shopping cart engines
• Forums and chat software
• Calendars
• Blogging software
• Directory services
• Email newsletters
• Data collection and reporting tools
• Banner advertising systems
• Subscription services
• & many, many more…

Monday, May 19, 2008

Internet Protocol

The Internet Protocol (IP) is the method or protocol by which data is sent from one computer to another on the Internet. Each computer (known as a host) on the Internet has at least one IP address that uniquely identifies it from all other computers on the Internet. When you send or receive data (for example, an e-mail note or a Web page), the message gets divided into little chunks called packets. Each of these packets contains both the sender's Internet address and the receiver's address. Any packet is sent first to a gateway computer that understands a small part of the Internet. The gateway computer reads the destination address and forwards the packet to an adjacent gateway that in turn reads the destination address and so forth across the Internet until one gateway recognizes the packet as belonging to a computer within its immediate neighborhood or domain. That gateway then forwards the packet directly to the computer whose address is specified.

Because a message is divided into a number of packets, each packet can, if necessary, be sent by a different route across the Internet. Packets can arrive in a different order than the order they were sent in. The Internet Protocol just delivers them. It's up to another protocol, the Transmission Control Protocol (TCP) to put them back in the right order.

IP is a connectionless protocol, which means that there is no continuing connection between the end points that are communicating. Each packet that travels through the Internet is treated as an independent unit of data without any relation to any other unit of data. (The reason the packets do get put in the right order is because of TCP, the connection-oriented protocol that keeps track of the packet sequence in a message.) In the Open Systems Interconnection (OSI) communication model, IP is in layer 3, the Networking Layer.

The most widely used version of IP today is Internet Protocol Version 4 (IPv4). However, IP Version 6 (IPv6) is also beginning to be supported. IPv6 provides for much longer addresses and therefore for the possibility of many more Internet users. IPv6 includes the capabilities of IPv4 and any server that can support IPv6 packets can also support IPv4 packets.

Sunday, May 18, 2008

SOAP

SOAP (Simple Object Access Protocol) is a way for a program running in one kind of operating system (such as Windows 2000) to communicate with a progam in the same or another kind of an operating system (such as Linux) by using the World Wide Web's Hypertext Transfer Protocol (HTTP)and its Extensible Markup Language (XML) as the mechanisms for information exchange. Since Web protocols are installed and available for use by all major operating system platforms, HTTP and XML provide an already at-hand solution to the problem of how programs running under different operating systems in a network can communicate with each other. SOAP specifies exactly how to encode an HTTP header and an XML file so that a program in one computer can call a program in another computer and pass it information. It also specifies how the called program can return a response.

SOAP was developed by Microsoft, DevelopMentor, and Userland Software and has been proposed as a standard interface to the Internet Engineering Task Force (IETF). It is somewhat similar to the Internet Inter-ORB Protocol (IIOP), a protocol that is part of the Common Object Request Broker Architecture (CORBA). Sun Microsystems' Remote Method Invocation (RMI) is a similar client/server interprogram protocol between programs written in Java.

An advantage of SOAP is that program calls are much more likely to get through firewall servers that screen out requests other than those for known applications (through the designated port mechanism). Since HTTP requests are usually allowed through firewalls, programs using SOAP to communicate can be sure that they can communicate with programs anywhere.

Saturday, May 17, 2008

Web Redirection

Method 1 - .htaccess 301 Redirect
The smoothest way to redirect your visitors is to use an .htaccess redirect. This has no delay since before a page is served to the browser the server checks first for an .htaccess file... if it sees this the old page never loads, instead visitors are sent directly to the new page.

These are a few .htaccess redirect codes that I've used that might come in handy for you. This is not a complete list by any means, but it took me ages to find how to do these so I'll save you the hassle and list them here. Oh, and please don't email me with questions about how these work, like I said, I found these with the help of others.. I have no idea in the slightest how to write this stuff and take no credit (or responsibility) for how they work.

If you're more technically minded than I am and want the information straight from the source, check the Apache Tutorial: .htaccess files for more detailed info.

Important notes about htaccess redirection

1. Always be sure to upload .htaccess files in ascii mode, sending it up as binary will break it (and usually make your server very, very unhappy.)
2. .htaccess does not work if you're on a windows server.
3. Make sure you triple check your changes. Clear your cache and look, test the server headers to make sure you see a 301 (that means its permanent) not a 302 (temporary) unless you are absolutely sure you really mean temporary.
4. Since some operating systems don't allow you to make a file without something before the "." you may need to save it as something.htaccess, some may even have to save it as htaccess.txt and change it once you've uploaded it.
5. Make sure your ftp program will show .htaccess files (FileZilla does and is free) It is a bit hard to edit something you can't see ;)
6. Double check that you're not overwriting an old one (some servers already place one there for your custom 404 pages etc.)
7. Make sure you replace example.com with your own sites URL ;-)
301 Redirect Examples
To Move a single page
Quick, easy and seamless for your visitors.
Redirect 301 /oldpage.html http://www.example.com/newpage.html
To Move an entire site
This will catch any traffic on your old site and redirect it to your index page on your new server. If you want to redirect each page to its new spot, this isn't the one for you.
Redirect 301 / http://www.example.com/
Changed file extension?
This example is perfect if you've decided to switch to .php from .html pages. It will look for any .html page and redirect it to .php (ie http://www.example.com/yourpage.html and redirect it to http://www.example.com/yourpage.php). Now, be careful with this, it does mean any html page. I did this on one of my sites and had totally forgotten I had an iframe with .html content on some pages... I didn't notice for weeks that it was broken :S.
So learn from my mistake ;-) check, double check, then check again.
RedirectMatch 301 (.*)\.html$ http://www.example.com$1.php
Redirect www to non www version of site
It's best to stick with either always using www.example.com or just example.com. Allowing both can confuse the search engines. So here's how to force your site to always show the non-www version. (Search for "canonical url errors" in your favorite search engine for more info.)
Note:
If you do use either of the next 2 codes below, and use a secure server (ie. https:) be sure to check that it doesn't redirect the secure to the insecure version. I'm pretty sure this will do that and that isn't something you want!

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^example\.com
RewriteRule (.*) http://example.com/$1 [R=301,L]

Redirect non-www to www

Same as above except in the reverse, this one forces the www. into your url.

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursite.com [NC]
RewriteRule ^(.*)$ http://www.yoursite.com/$1 [L,R=301]

Method 2 - Meta Redirect
I'd really advise against redirecting this way! Most search engine are having difficulties with this one (and spammers have been using this in very bad ways) and it might get your page in a heap of trouble! Some browsers also don't read it properly so your would-be visitors may get stranded. Seriously, it really isn't advisable to use this anymore but if you insist on trying it, here it is.
meta http-equiv="refresh" content="10; url=http://example.com/"
Content="10; tells the browser to wait 10 seconds before transfer, choose however long you would like, you can even choose 0 to give a smoother transition.

Friday, May 16, 2008

Are You Planning to Switch Job

You spend a large percentage of your waking hours at your job. How happy are you there? Will you be happier in a new job? To switch or not to switch is the perennial question many of us face today.

If your job isn't working for you, don't panic or take it personally. A large percentage of employees switch jobs in such conditions. But, before you reach that decision, it is important to evaluate certain aspects -

Are you a chronic job-switcher?

"Whether it's for a good reason or bad, switching jobs is extremely common nowadays, especially in some professions -- software for example. The days when people kept only one job throughout their lives are gone. Today, the average CV usually contains several moves, especially early on in a career. In fact, it's even considered unambitious to spend too many years in one job," says Manisha Dutt, 29, a manager with a software firm in Gurgaon.

However, an extreme case of 'job hopping,' such as one every year or even several times a year, definitely won't reflect well on your resume, especially if you are under 30. "This is because a company also spends a considerable amount on training new employees and is always looking at reducing employee turnover. In such a case, one look at your resume, and they may run in the other direction," says Kesarwani.

Circumstances that demand a job change and those that don't -

Some circumstances may warrant a job change, but others can be remedied. "The reason to get you to switch needs to be big -- reasons like lack of opportunities for growth, a move necessitated for family/ health reasons, need for a better salary, etc. Alternatively, you may know for sure that the new company is a great place to work in," says Pankaj Sharma, 27, an independent recruitment consultant in Delhi.

Questions to ask yourself -
Ask yourself the following questions regarding where you are at present (and be honest with your answers) -

*
Do I really like my current job?
*
Do I enjoy working with my colleagues?
*
If I stay here, where will I be in two years time?
*
Could I be earning more elsewhere?
*
What are the intangible benefits of working here?
*
Is the technology one that I would like to align myself with in the future?

Answer the questions using these broad parameters -

*
Job quality (Is this what I want to do?)
*
Growth prospects (Can I stay in this job? Can I move up?)
*
More money (How much is enough?)
*
Mental stimulation
*
The importance of money.

Money is good stuff - it pays for nice vacations, cool cars, education for your children, etc. Don't discount the money factor, especially if others are depending on you.

"No matter what any one says, money does buy happiness. When you accumulate a significant amount as a buffer between yourself and poverty, and stop living one pay cheque at a time, your life completely changes. You gain the freedom to pursue other avenues, like your own business, a career change, a personal project, or a mentally enriching educational experience. Such freedom is an incomparable source of happiness and tranquility, and only money can grant it," says Kesarwani.

However, if the new place totally rocks, you might consider working there and even taking a salary cut to jump ship if your current job is indeed a living nightmare.

Do a cost-benefit analysis -

Let's say you take home Rs 30,000 per month. You are offered a 20 per cent salary hike in the new job and see yourself now taking home Rs 36,000 a month. What will that extra Rs 6,000 a month (= Rs 72,000 a year) do for you?

Will you blow it all on a plasma TV, stash it all in savings for an early retirement, eat out two or three more times a week, or go partying with your friends?

What is the bottomline impact on your lifestyle that this raise will give you? How will this raise impact your work environment? Keeping in mind that you work eight hours or more a day, are these extras worth the anxiety and the risk involved in switching jobs? What risks do you have if you stay in your current job? In short, what is the opportunity cost?

To cut to the chase, don't move only for financial reasons unless you're going to earn significantly more. Happiness, in terms of liking what you are doing and feeling that you are accomplishing something, is much more important. Eventually, the money won't be motivation enough to continue with the new job.

Weigh the risks -

Consider this - you already know what your current job is like and you like it. You know the people and get along with your colleagues, who are interesting people. Your boss treats you well.

The new place might be even better and the offer may be 20 per cent more than what you're getting now. The people might all be nice, or there may be a few nut cases and backstabbers there. Your boss may steal the credit for the work you do.

"Switching is a big risk; you are going out into the unknown. Chances are, the new place can be worse," says Sharma, who has experienced this himself.

"Verify everything the potential boss tells you. Bosses try to make the job sound attractive in the same way that job applicants try to make themselves sound good," says Dutt.

If you don't really want to quit -

"The first step is to analyse why, and whether or not you really want to leave. Is it just because of one thing, such as a low salary or an interpersonal conflict? If so, you must communicate that to your manager and HR department. It could be better to first consider options such as moving to another department, or negotiating a salary hike rather than leaving the organisation," feels Dutt.

Most problems at the workplace can be solved if both parties are willing to solve them. "A three-month trial can be experimented with to see if the situation can be resolved. Just like problems take time to develop, their solutions also take time to work," says Kesarwani.

Keep your relationship with your colleagues and your company intact -

The way in which you carry yourself during your transition can have a great impact on your career. It says as much about you professionally as the impression you had made on your first day. The people who you work with will make it a point to note your behaviour. If it is anywhere inappropriate or negative, the word can spread quickly. Keep in mind that this group you leave includes potential references.

"Your last impression is just about as important as your first. It's vital to break away without any ill feeling, and leave behind an impeccable record. It's a small world and it could just happen that you work with, or for, the very same people again," says Sharma.

So, it's important to leave on positive terms. Display professionalism. The right attitude is critical to building bridges, and not burning them, when you are at the threshold of assuming a new position.

The guilt factor -

"Only three months into my first job, I landed a new opportunity offering me 30 to 40 per cent more than my current job. I felt really bad leaving my current job and disappointing the people that gave me a chance to work there," says Dutt.

"As for feeling bad about leaving, don't get all flustered about it. Everyone needs to grow, and employers themselves are aware of that," says Sharma. "The key for you is to determine whether it's the wrong job, the wrong employer, or the wrong career. Once you have made that decision, the ideal scenario is to locate a new job while you are still employed. Then, if you think what you get is better than your current job, don't feel guilty -- take it. They'll understand

Advantages of MYSQL 5 over MYSQL 4

o Stored procedures
o Triggers
o Views
Lets first take a look at stored procedures. Stored procedures have many benefits in terms of performance and security. A stored procedure is a procedure that is that is stored in a database. This is sort of like a function or sub-routine in a regular computer language. Like functions in other languages, stored procedures come in two flavors, those that you call to perform a task or those that you call to return a value that you use in another part of the query. The main reason why you should use stored procedures is because of speed. Stored procedures are stored on the server so if you need to do a certain task over and over again, stored procedures will give great boosts in speed and also put less of a burden on the server because it will not need to send messages back and forth to the client machine since its all on the server side. Another advantage is that stored procedures are common throughout all MYSQL deployments. You never have to install an extension class or add-on feature to any MYSQL setup to get stored procedures to work. Not only will they work in all deployments of MYSQL, but since MYSQL uses standard SQL syntax and stored procedures are largely the same throughout any SQL database, you should be able to port your stored procedure code easily into either MSSQL, Oracle 10g or any other SQL based system.
The second advantage we are going to look at in MYSQL 5 are triggers. A trigger is a piece of procedural code that is automatically executed in response to certain events that happen on a table or in a database. Triggers give programmers more control over what happens when a specific alteration is made to a table. It also can restrict access to specific data, perform logging, or audit data modifications.
The final advantage that we will examine here are views. Views are a handy programming tool that MYSQL 5 developers can use to show actual code directly from the screen of the client program. This is useful for debugging and troubleshooting. Views are also often used to help write queries. There have been some performance problems with using the view function, but those will soon be resolved.
With these three advantages, MYSQL 5 is definitely a step beyond MYSQL 4 and worth an upgrade now.

Thursday, May 15, 2008

What's New in PHP 5

Introduction

Only time will tell if the PHP 5 release will be as successful as the releases of its two predecessors (PHP 3 and PHP 4). The new features and changes aim to rid PHP of any weaknesses it may have had and make sure that it stays in the lead as the best web scripting language on the globe.

This book covers PHP 5 and its new features in great detail. However, for those of you familiar with PHP 4, and are eager to know what is new in PHP 5, then this chapter is for you.

The chapter will cover:

  • The new language features
  • News concerning PHP extensions

Language Features

New Object Oriented model

When Zeev Suraski added the object-oriented syntax back in the days of PHP 3, it was added as "syntactic sugar for accessing collections". The object-oriented model also had support for inheritance and allowed a class (and object) to aggregate both methods and properties, but not much more. When Zeev and Andi rewrote the scripting engine for PHP 4, it was a completely new engine, running much faster, much more stable and with many more features. However, the object-oriented model first introduced in PHP 3, was barely touched.

Although the object model had serious limitations it was used extensively around the world, often in very large PHP applications. This impressive use of the OOP paradigm with PHP 4 despite its weaknesses led to it being the main focus for the PHP 5 release.

So what were some of the limitations in PHP 3 and 4? The biggest limitation (which led to further limitations) was the fact that the copy semantics of objects were the same as for native types. So how did this actually affect the PHP developer? When you'd assign a variable (that points to an object) to another variable, a copy of the object would be created. Not only did this impact performance but it usually also lead to obscure behavior and bugs in PHP 4 applications because many developers thought that both variables would be pointing at the same object which wasn't the case. They were pointing at separate copies of the same object, changing one would not change the other.

For example:

class Person {
var
$name;
function
getName() {
return
$this->name;
}
function
setName($name) {
$this->name = $name;
}
function
Person($name) {
$this->setName($name);
}
}

function
changeName($person, $name) {
$person->setName($name);
}

$person = new Person("Andi");
changeName($person, "Stig");
print
$person->getName();

In PHP 4, this piece of code would print out "Andi". The reason is that we pass the object $person to the changeName() function by-value, and thus, $person is copied and changeName() works on a copy of $person.

This behavior is not very intuitive, as many developers would expect the Java-like behavior. In Java variables actually hold a handle (or pointers) to the object, and therefore, when it is copied only the handle and not the entire object is duplicated.
There were two kinds of users in PHP 4, the ones who were aware of this problem and the ones who weren't. The latter would usually not notice this problem and their code was written in a way where it didn't really matter if the problem existed or not. Surely some of these people had sleepless nights trying to track down weird bugs which they couldn't pinpoint. The former group dealt with this problem by always passing and assigning objects by reference. This would prevent the engine from copying their objects but would be quite a headache as the code included numerous
& signs.

The old object model not only led to the above-mentioned problems but also led to fundamental problems that prevented implementing some additional features on top of the existing object model.

In PHP 5, the infrastructure of the object model was rewritten to work with object handles. Unless you explicitly clone an object by using the clone keyword you will never create behind the scene duplicates of your objects. In PHP 5, there is neither a need to pass objects by reference nor assigning them by reference.

Note: Passing by reference and assigning by reference is still supported, in case you want to actually change a variable's content (whether object or other type).

New Object Oriented Features

The new object oriented features are too numerous to give a detailed description in this section. The object oriented language chapter goes over each feature in detail.

The following is a list of the main new features:

1. public/private/protected access modifiers for methods and properties

Allows the use of common OO access modifiers to control access to methods and properties.

class MyClass {
private
$id = 18;

public function
getId() {
return
$this->id;
}
}

2. Unified constructor name __construct()

Instead of the constructor being the name of the class, it should now be declared as __construct(), making it easier to shift classes inside class hierarchies.

class MyClass {
function
__construct() {
print
"Inside constructor";
}
}

3. Object destructor support by defining a __destructor() method

Allows defining a destructor function that runs when an object is destroyed.



class MyClass {
function
__destruct() {
print
"Destroying object";
}
}

?>

4. Interfaces

Gives the ability for a class to fulfill more than one is-a relationships. A class can inherit from one class only but may implement as many interfaces as it wants.

interface Display {
function
display();
}

class
Circle implements Display {
function
display() {
print
"Displaying circle ";
}
}

5. instanceof operator

Language level support for is-a relationship checking. The PHP 4 is_a() function is now deprecated.

if ($obj instance of Circle) {
print
'$obj is a Circle';
}

6. final methods

The final keyword allows you to mark methods so that an inheriting class can't overload them.

class MyClass {
final function
getBaseClassName() {
return
__CLASS__;
}
}

7. final classes

After declaring a class as final, it can't be inherited. The following example would error out:

final class FinalClass {
}

class
BogusClass extends FinalClass {
}

8. Explicit object cloning

In order to clone an object you have to use the clone keyword. You may declare a __clone() method which will be called during the clone process (after the properties have been copied from the original object).

class MyClass {
function
__clone() {
print
"Object is being cloned";
}
}
$obj = new MyClass();
clone
$obj;

9. Class constants

Classes definitions can now include constant values, and are referenced using the class.

class MyClass {
const
SUCCESS = "Success";
const
FAILURE = "Failure";
}
print
MyClass::SUCCESS;

10. Static members

Classes definitions can now include static members (properties), accessible via the class. Common usage of static members is in the Singleton pattern.

class Singleton {
static private
$instance = NULL;

private function
__construct() {
}

static public function
getInstance() {
if (
self::$instance == NULL) {
self::$instance = new Singleton();
}
return
self::$instance;
}
}

11. Static methods

You can now define methods as static allowing them to be called from non-object context. Static methods don't define the $this variable as they aren't bound to any specific object.



class MyClass {
static function
helloWorld() {
print
"Hello, world";
}
}
MyClass::helloWorld();

?>

12. abstract classes

A class may be declared as abstract so as to prevent it from being instantiated. However, you may inherit from an abstract class.

abstract class MyBaseClass {
function
display() {
print
"Default display routine being called";
}
}

13. abstract methods

A method may be declared as abstract, thereby deferring its definition to an inheriting class. A class that includes abstract methods must be declared as abstract.

abstract class MyBaseClass {
abstract function
display();
}

14. Class type hints

Function declarations may include class type hints for their parameters. If the functions are called with an incorrect class type an error occurs.

function expectsMyClass(MyClass $obj) {

}

15. Support for dereferencing objects which are returned from methods.

In PHP 4, you could not directly dereference objects which are returned from methods. You would have to first assign the object to a dummy variable and then dereference it.
PHP 4:

$dummy = $obj->method();
$dummy->method2();

PHP 5:

$obj->method()->method2();

16. Iterators

PHP 5 allows both PHP classes and PHP extension classes to implement an Iterator interface. Once you implement this interface you will be able to iterate instances of the class by using the foreach() language construct.

$obj = new MyIteratorImplementation();
foreach (
$obj as $value) {
print
"$value";
}

For a more complete example, please refer to the "Advanced OOP & Design Patterns" chapter.

17. __autoload()

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class). In PHP 5, this is no longer necessary. You may define an __autoload() function which is automatically called in case you are trying to use a class which hasn't been defined yet. By calling this function the scripting engine is giving a last chance to load the class before PHP bails out with an error.

function __autoload($class_name) {
include_once(
$class_name . "php");
}

$obj = new MyClass1();
$obj2 = new MyClass2();

Other New Language Features

1. Exception handling

PHP 5 adds the ability for the well known try/throw/catch structured exception handling paradigm. You are only allowed to throw objects which inherit from the Exception class.

class SQLException extends Exception {
public
$problem;
function
__construct($problem) {
$this->problem = $problem;
}
}

try {
...
throw new SQLException("Couldn't connect to database");
...
}
catch (SQLException $e) {
print
"Caught an SQLException with problem $obj->problem";
}
catch (Exception $e) {
print
"Caught unrecognized exception";
}

Currently for backwards compatibility purposes most internal functions do not throw exceptions. However, new extensions are making use of this capability and you can use it in your own source code. Also, similar to the already existing set_error_handler() you may use set_exception_handler() to catch an unhandled exception before the script terminates.

2. foreach with references

In PHP 4, you could not iterate through an array and modify its values. PHP 5 supports this by allowing you to mark the foreach() loop with the & (reference) sign, thus making any values you change affect the array you're iterating over.

foreach ($array as &$value) {
if (
$value === "NULL") {
$value = NULL;
}
}

3. default values for by-reference parameters

In PHP 4, default values could only be given to parameters which are passed by-value. Giving default values to by-reference parameters is now supported.

function my_func(&$arg = null) {
if (
$arg === NULL) {
print
'$arg is empty';
}
}
my_func();

General PHP changes

XML and Web Services

Following the changes in the language, the XML updates in PHP 5 are most probably the most significant and exciting. The enhanced XML functionality in PHP 5 puts it on par with other web technologies in some areas and overtakes them in others.

The Foundation

XML support in PHP 4 was implemented using a variety of underlying XML libraries. SAX support was implemented using the old Expat library, XSLT was implemented using the Sablotron library (or using libxml2 via the DOM extension) and DOM was implemented using the more powerful libxml2 library by the GNOME project.

Using a variety of libraries did not make PHP 4 excel when it came to XML support. Maintenance was poor, new XML standards weren't always supported, performance wasn't as good as it could have been, and interoperability between the varies XML extensions did not exist.

In PHP 5, all XML extensions have been rewritten to use the superb libxml2 XML toolkit (http://www.xmlsoft.org/). It is a very feature rich, highly maintained and efficient implementation of the XML standards bringing the cutting edge of XML technology to PHP.
All the above mentioned extensions (SAX, DOM and XSLT) now use libxml2 including the new additional extensions SimpleXML and SOAP.

SAX

As mentioned, the new SAX implementation has switched from using Expat to libxml2. Although the new extension should be compatible there may be some small subtle differences. Developers who still want to work with the Expat library can do so by configuring and building PHP accordingly (not recommended).

DOM

Although DOM support in PHP 4 was also based on the libxml2 library, it was quite buggy, had memory leaks and the API in many cases was not W3C compliant. The DOM extension went through a thorough facelift for PHP 5. Not only was the extension mostly rewritten it is now also W3C complaint. For example, function names now use studlyCaps as described by the W3C standard making it easier for you to read general W3C documentation and implementing what you learnt, right away in PHP. In addition, the DOM extension now supports three kinds of schemas for XML validation, DTD, XML Schema and RelaxNG.

As a result of these changes PHP 4 code using DOM will not always run in PHP 5. However, in most cases adjusting the function names to the new standard will probably do the trick.

XSLT

In PHP 4, there were two extensions that supported XSL Transformations. The first was using the Sablotron extension and the second was using the XSLT support in the DOM extension. In PHP 5, a new XSL extension was written and, as mentioned, is based on the libxml2 extension. As in PHP 5, the XSL Transformation does not take the XSLT stylesheet as a parameter but depends on the DOM extension to load it, the stylesheet can be cached in memory and may be applied to many documents saving execution time

SimpleXML

Probably when looking back in a year or two it will be clear that SimpleXML has revolutionized the way PHP developers work with XML files. SimpleXML could really be called "XML for Dummies". Instead of having to deal with DOM or even worse SAX, SimpleXML represents your XML file as a native PHP object. You can read, write or iterate over your XML file with ease accessing elements and attributes.

Consider the following XML file:

<clients>
<
client>
<
name>John Doename>
<
account_number>87234838account_number>
client>
<
client>
<
name>Janet Smithname>
<
account_number>72384329account_number>
client>
clients>

The following piece of code prints each client's name and account number:

$clients = simplexml_load_file('clients.xml');
foreach (
$clients->client as $client) {
print
"$client->name has account number $client->account_number ";
}

It's obvious how simple SimpleXML really is.

And in case there is something advanced you need to do to your SimpleXML object which isn't supported in this lightweight extension, you can convert it to a DOM tree by calling dom_import_simplexml(), manipulate it in DOM and covert it back to SimpleXML using simplexml_import_dom(). Thanks to both extensions using the same underlying XML library switching between these two has been made a reality.

SOAP

Official native SOAP support in PHP 4 was lacking. The most commonly used SOAP implementation was PEAR's but as it was implemented entirely in PHP it could not perform as well as a built-in C extension. Other available C extensions never reached stability and wide adoption and, therefore, were not included in the main PHP 5 distribution.

SOAP support in PHP 5 was completely rewritten as a C extension and, although it was only completed at a very late stage in the beta process, it was incooperated into the default distribution due to its thorough implementation of most of the SOAP standard.

The following calls SomeFunction() defined in a WSDL file:

$client = new SoapClient("some.wsdl");
$client->SomeFunction($a, $b, $c);