8 Great CSS Frameworks

Posted on June 26th, 2008 in Frameworks, HTML by Ashish  Tagged ,

Well, I guess I’m going to work backwords. There are three layers to the frontend; behaviour, presentation and markup. We’ve done behavior so we’re onto presentational now. CSS Frameworks have been all the buzz lately, we’ve had ones that use python ways of code then regenerate it as css, ones that are specifically for forms and an awesome one which is just for styling print!

Personally I find frameworks to much hassle, I have my own little framework but that is only really 20 or so lines. I might share it with all of you in the coming weeks if you would like it. Now here they are!

1. 960 Grid System - The 960 Grid System is an effort to streamline web development workflow by providing commonly used dimensions, based on a width of 960 pixels. There are two variants: 12 and 16 columns, which can be used separately or in tandem.

2. Blueprint CSS - Blueprint is a CSS framework, which aims to cut down on your CSS development time. It gives you a solid CSS foundation to build your project on top of, with an easy-to-use grid, sensible typography, and even a stylesheet for printing.

3. Hartija – The owner of Hartija describes it as a “universal Cascading Style Sheets for web printing”. It’s extremely customizable and very user friendly.

4. Formy CSS – Formy is mini CSS Framework for building web forms.

5. Clever CSS – CleverCSS is a small markup language for CSS inspired by Python that can be used to build a style sheet in a clean and structured way. In many ways it’s cleaner and more powerful than CSS2 is.

6. SenCSS – SenCSS is a sensible standards CSS Framework. This means that SenCSS tries to supply standard styling for all repetitive parts of your CSS, allowing you to focus on the fun parts. In that sense, senCSS is a bit like a large CSS Reset.

7. Elements -

Elements is a down to earth CSS framework. It was built to help designers write CSS faster and more efficient. Elements goes beyond being just a framework, it’s its own project workflow.It has everything you need to complete your project, which makes you and your clients happy. Read the Overview for more information.

8. LogicCSS – The Logic CSS framework is a collection of CSS files and PHP utilities to cut development times for web-standards compliant xHTML layouts.

This is just the tip of the iceberg, there are tones more css frameworks out there. I plan on releasing one for this site.

All about Extensible Markup Language (XML)

Posted on March 6th, 2008 in XML by Ashish  Tagged , , , ,

Extensible Markup Language (XML) is a general-purpose specification for creating custom markup languages. It is classified as an extensible language because it allows its users to define their own elements. Its primary purpose is to facilitate the sharing of structured data across different information systems, particularly via the Internet, and it is used both to encode documents and to serialize data.

well-formedness is required, XML is a generic framework for storing any amount of text or any data whose structure can be represented as a tree. The only indispensable syntactical requirement is that the document has exactly one root element (alternatively called the document element). This means that the text must be enclosed between a root start-tag and a corresponding end-tag. The following is a "well-formed" XML document:

<book>This is a book…. </book>

The root element can be preceded by an optional XML declaration. This element states what version of XML is in use (normally 1.0); it may also contain information about character encoding and external dependencies.

<?xml version="1.0" encoding="UTF-8"?>

Here is an example of a structured XML document:

<recipe name="bread" prep_time="5 mins" cook_time="3 hours">
   <title>Basic bread</title>
   <ingredient amount="3" unit="cups">Flour</ingredient>
   <ingredient amount="0.25" unit="ounce">Yeast</ingredient>
   <ingredient amount="1.5" unit="cups" state="warm">Water</ingredient>
   <ingredient amount="1" unit="teaspoon">Salt</ingredient>
   <instructions>
     <step>Mix all ingredients together.</step>
     <step>Knead thoroughly.</step>
     <step>Cover with a cloth, and leave for one hour in warm room.</step>
     <step>Knead again.</step>
     <step>Place in a bread baking tin.</step>
     <step>Cover with a cloth, and leave for one hour in warm room.</step>
     <step>Bake in the oven at 350°F for 30 minutes.</step>
   </instructions>
 </recipe>

Entity references

An entity in XML is a named body of data, usually text. Entities are often used to represent single characters that cannot easily be entered on the keyboard; they are also used to represent pieces of standard ("boilerplate") text that occur in many documents, especially if there is a need to allow such text to be changed in one place only.

Special characters can be represented either using entity references, or by means of numeric character references. An example of a numeric character reference is "€", which refers to the Euro symbol by means of its Unicode codepoint in hexadecimal.

An entity reference is a placeholder that represents that entity. It consists of the entity’s name preceded by an ampersand ("&") and followed by a semicolon (";"). XML has five predeclared entities:
&amp;     &     ampersand
&lt;     <     less than
&gt;     >     greater than
&apos;     ‘     apostrophe
&quot;     "     quotation mark

Here is an example using a predeclared XML entity to represent the ampersand in the name "AT&T":

<company_name>AT&amp;T</company_name>

Additional entities (beyond the predefined ones) can be declared in the document’s Document Type Definition (DTD). A basic example of doing so in a minimal internal DTD follows. Declared entities can describe single characters or pieces of text, and can reference each other.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE example [
    <!ENTITY copy "©">
    <!ENTITY copyright-notice "Copyright &copy; 2006, hurricanesoftwares.com">
]>
<example>
    &copyright-notice;
</example>

When viewed in a suitable browser, the XML document above appears as:

<example> Copyright © 2006, Hurricanesoftwares.com </example>

Numeric character references

Numeric character references look like entity references, but instead of a name, they contain the "#" character followed by a number. The number (in decimal or "x"-prefixed hexadecimal) represents a Unicode code point. Unlike entity references, they are neither predeclared nor do they need to be declared in the document’s DTD. They have typically been used to represent characters that are not easily encodable, such as an Arabic character in a document produced on a European computer. The ampersand in the "AT&T" example could also be escaped like this (decimal 38 and hexadecimal 26 both represent the Unicode code point for the "&" character):

<company_name>AT&T</company_name>
<company_name>AT&T</company_name>

Well-formed documents

In XML, a well-formed document must conform to the following rules, among others:

    * Non-empty elements are delimited by both a start-tag and an end-tag.
    * Empty elements may be marked with an empty-element (self-closing) tag, such as <IAmEmpty />. This is equal to <IAmEmpty></IAmEmpty>.
    * All attribute values are quoted with either single (’) or double (") quotes. Single quotes close a single quote and double quotes close a double quote.
    * Tags may be nested but must not overlap. Each non-root element must be completely contained in another element.
    * The document complies with its declared character encoding. The encoding may be declared or implied externally, such as in "Content-Type" headers when a document is transported via HTTP, or internally, using explicit markup at the very beginning of the document. When no such declaration exists, a Unicode encoding is assumed, as defined by a Unicode Byte Order Mark before the document’s first character. If the mark does not exist, UTF-8 encoding is assumed.

Element names are case-sensitive. For example, the following is a well-formed matching pair:

    <Step> … </Step>

whereas this is not

    <Step> … </step>

By carefully choosing the names of the XML elements one may convey the meaning of the data in the markup. This increases human readability while retaining the rigor needed for software parsing.

Choosing meaningful names implies the semantics of elements and attributes to a human reader without reference to external documentation. However, this can lead to verbosity, which complicates authoring and increases file size.

Automatic verification

It is relatively simple to verify that a document is well-formed or validated XML, because the rules of well-formedness and validation of XML are designed for portability of tools. The idea is that any tool designed to work with XML files will be able to work with XML files written in any XML language (or XML application). One example of using an independent tool follows:

    * load it into an XML-capable browser, such as Firefox or Internet Explorer
    * use a tool like xmlwf (usually bundled with expat)
    * parse the document, for instance in Ruby:

irb> require "rexml/document"
irb> include REXML
irb> doc = Document.new(File.new("test.xml")).root

Displaying XML on the web

XML documents do not carry information about how to display the data. Without using CSS or XSL, a generic XML document is rendered as raw XML text by most web browsers. Some display it with ‘handles’ (e.g. + and – signs in the margin) that allow parts of the structure to be expanded or collapsed with mouse-clicks.

In order to style the rendering in a browser with CSS, the XML document must include a reference to the stylesheet:

<?xml-stylesheet type="text/css" href="myStyleSheet.css"?>

Note that this is different from specifying such a stylesheet in HTML, which uses the <link> element.

Extensible Stylesheet Language (XSL) can be used to alter the format of XML data, either into HTML or other formats that are suitable for a browser to display.

To specify client-side XSL Transformation (XSLT), the following processing instruction is required in the XML:

<?xml-stylesheet type="text/xsl" href="myTransform.xslt"?>

Client-side XSLT is supported by many web browsers. Alternatively, one may use XSL to convert XML into a displayable format on the server rather than being dependent on the end-user’s browser capabilities. The end-user is not aware of what has gone on ‘behind the scenes’; all they see is well-formatted, displayable data.

Processing XML files

Three traditional techniques for processing XML files are:

    * Using a programming language and the SAX API.
    * Using a programming language and the DOM API.
    * Using a transformation engine and a filter

More recent and emerging techniques for processing XML files are:

    * Pull Parsing
    * Data binding

Simple API for XML (SAX)

SAX is a lexical, event-driven interface in which a document is read serially and its contents are reported as "callbacks" to various methods on a handler object of the user’s design. SAX is fast and efficient to implement, but difficult to use for extracting information at random from the XML, since it tends to burden the application author with keeping track of what part of the document is being processed. It is better suited to situations in which certain types of information are always handled the same way, no matter where they occur in the document.

DOM

DOM is an interface-oriented Application Programming Interface that allows for navigation of the entire document as if it were a tree of "Node" objects representing the document’s contents. A DOM document can be created by a parser, or can be generated manually by users (with limitations). Data types in DOM Nodes are abstract; implementations provide their own programming language-specific bindings. DOM implementations tend to be memory intensive, as they generally require the entire document to be loaded into memory and constructed as a tree of objects before access is allowed. DOM is supported in Java by several packages that usually come with the standard libraries. As the DOM specification is regulated by the World Wide Web Consortium, the main interfaces (Node, Document, etc.) are in the package org.w3c.dom.*, as well as some of the events and interfaces for other capabilities like serialization (output). The package com.sun.org.apache.xml.internal.serialize.* provides the serialization (output capacities) by implementing the appropriate interfaces, while the javax.xml.parsers.* package parses data to create DOM XML documents for manipulation.

Transformation engines and filters

A filter in the Extensible Stylesheet Language (XSL) family can transform an XML file for displaying or printing.

    * XSL-FO is a declarative, XML-based page layout language. An XSL-FO processor can be used to convert an XSL-FO document into another non-XML format, such as PDF.
    * XSLT is a declarative, XML-based document transformation language. An XSLT processor can use an XSLT stylesheet as a guide for the conversion of the data tree represented by one XML document into another tree that can then be serialized as XML, HTML, plain text, or any other format supported by the processor.
    * XQuery is a W3C language for querying, constructing and transforming XML data.
    * XPath is a DOM-like node tree data model and path expression language for selecting data within XML documents. XSL-FO, XSLT and XQuery all make use of XPath. XPath also includes a useful function library.

Pull parsing

Pull parsing [6] treats the document as a series of items which are read in sequence using the Iterator design pattern. This allows for writing of recursive-descent parsers in which the structure of the code performing the parsing mirrors the structure of the XML being parsed, and intermediate parsed results can be used and accessed as local variables within the methods performing the parsing, or passed down (as method parameters) into lower-level methods, or returned (as method return values) to higher-level methods. Examples of pull parsers include StAX in the Java programming language, SimpleXML in PHP and System.Xml.XmlReader in .NET.

A pull parser creates an iterator that sequentially visits the various elements, attributes, and data in an XML document. Code which uses this ‘iterator’ can test the current item (to tell, for example, whether it is a start or end element, or text), and inspect its attributes (local name, namespace, values of XML attributes, value of text, etc.), and can also move the iterator to the ‘next’ item. The code can thus extract information from the document as it traverses it. The recursive-descent approach tends to lend itself to keeping data as typed local variables in the code doing the parsing, while SAX, for instance, typically requires a parser to manually maintain intermediate data within a stack of elements which are parent elements of the element being parsed. Pull-parsing code can be more straightforward to understand and maintain than SAX parsing code.

Data binding

Another form of XML Processing API is data binding, where XML data is made available as a custom, strongly typed programming language data structure, in contrast to the interface-oriented DOM. Example data binding systems include the Java Architecture for XML Binding (JAXB).

Non-extractive XML Processing API

Non-extractive XML Processing API is a new and emerging category of parsers that aim to overcome the fundamental limitations of DOM and SAX. The most representative is VTD-XML, which abolishes the object-oriented modeling of XML hierarchy and instead uses 64-bit Virtual Token Descriptors (encoding offsets, lengths, depths, and types) of XML tokens. VTD-XML’s approach enables a number of interesting features/enhancements, such as high performance, low memory usage, ASIC implementation, incremental update, and native XML indexing .

Specific XML applications and editors

The native file format of OpenOffice.org, AbiWord, and Apple’s iWork applications is XML. Some parts of Microsoft Office 2007 are also able to edit XML files with a user-supplied schema (but not a DTD), and Microsoft has released a file format compatibility kit for Office 2003 that allows previous versions of Office to save in the new XML based format. There are dozens of other XML editors available.

Advantages of XML

    * It is text-based.
    * It supports Unicode, allowing almost any information in any written human language to be communicated.
    * It can represent common computer science data structures: records, lists and trees.
    * Its self-documenting format describes structure and field names as well as specific values.
    * The strict syntax and parsing requirements make the necessary parsing algorithms extremely simple, efficient, and consistent.
    * XML is heavily used as a format for document storage and processing, both online and offline.
    * It is based on international standards.
    * It can be updated incrementally.
    * It allows validation using schema languages such as XSD and Schematron, which makes effective unit-testing, firewalls, acceptance testing, contractual specification and software construction easier.
    * The hierarchical structure is suitable for most (but not all) types of documents.
    * It is platform-independent, thus relatively immune to changes in technology.
    * Forward and backward compatibility are relatively easy to maintain despite changes in DTD or Schema.
    * Its predecessor, SGML, has been in use since 1986, so there is extensive experience and software available.
    * An element fragment of a well-formed XML document is also a well-formed XML document.

Disadvantages of XML

    * XML syntax is redundant or large relative to binary representations of similar data, especially with tabular data.
    * The redundancy may affect application efficiency through higher storage, transmission and processing costs.
    * XML syntax is verbose, especially for human readers, relative to other alternative ‘text-based’ data transmission formats.
    * The hierarchical model for representation is limited in comparison to an object oriented graph.
    * Expressing overlapping (non-hierarchical) node relationships requires extra effort.
    * XML namespaces are problematic to use and namespace support can be difficult to correctly implement in an XML parser.
    * XML is commonly depicted as "self-documenting" but this depiction ignores critical ambiguities.
    * The distinction between content and attributes in XML seems unnatural to some and makes designing XML data structures harder

CakePHP Naming Conventions, Global Constants, Global Functions

Posted on March 3rd, 2008 in Frameworks by Ashish  Tagged , , ,

config (’file_name’)

Global Functions

up (’string’) r (’search’, ‘replace’, ‘text’) pr (array) am (array, [array, array]) env (’HTTP_HEADER’)

cache (path, data, expires, [target])

Models

Class Name: singular, camel cased (LineItem, Person) File Name: singular, underscored (line_item.php, person.php) Table Name: plural, underscored (line_items, people)

Controllers

Class Name: plural, camel cased, ends in "Controller"

Views

Path: controller name, underscored (app/views/line_items/<file>, app/ views/people/<file>) File Name: action name, lowercase (index.thtml, view.thtml)

uses (’file_name’) vendor (’file_name’) debug (’message’) a (element, [element, element]) aa (key, value, [key, value]) e (’message’) low (’STRING’)

(LineItemsController, People Controller)

File Name: plural, underscored

(line_items_controller.php, people_controller.php)

clearCache ([params, type, ext]) countdim (array)

Model

Properties $cacheQueries $data $displayField $id $name $primaryKey Methods $recursive $useDbConfig $useTable $validate $validationErrors $_tableInfo Association Properties $belongsTo $hasAndBelongsToMany $hasMany $hasOne

Controller

Properties $name $autoLayout $base $cacheAction $data $here $output $params $plugin $view $webroot Methods $action $autoRender $beforeFilter $components $helpers $layout $pageTitle $persistModel $uses $viewPath Properties $action $autoRender $controller $hasRendered $here $loaded $name $params $plugin $themeWeb $viewPath Methods

View

$autoLayout $base $ext $helpers $layout $models $pageTitle $parent $subDir $uses

bindModel (params) create ( ) delete (id, [cascade]) escapeField (field) execute (data) exists ( ) field (name, conditions, order) find ([conditions, fields, order, recursive])

findAll ([conditions, fields, order, limit, page, recur...])

getLastInsertID ( ) getNumRows ( ) hasAny ([conditions]) hasField (name) invalidate (field) invalidFields ([data]) isForeignKey (field) loadInfo ( ) query ([sql]) read ([fields, id]) remove ([id, cascade]) save ([data, validate, fieldList]) saveField ([name, value, validate]) set (one, [two]) setDataSource (dataSource) setSource (tableName) unbindModel (params) validates ([data])

findAllThreaded([conditions, fields, sort]) findCount ([conditions, recursive]) findNeighbours (conditions, field, value)

generateList ([conditions, order, limit, keyPath, val...])

getAffectedRows ( ) getColumnType (column) getColumnTypes ( ) getDisplayField ( ) getID ([list])

cleanUpFields ( ) constructClasses ( ) flash (message, url, [pause]) flashOut (message, url, [pause]) generateFieldNames (data, doCreateO…) postConditions (data) redirect (url, [status]) referer ([default, local]) render([action, layout, file]) set (one, [two]) setAction (action, [param, param, param]) validate ( ) validateErrors ( )

element (name) error (code, name, message) pluginView (action, layout) render ([action, layout, file]) renderCache (filename, timeStart) renderElement (name, [params]) renderLayout (content_for_layout) setLayout (layout)

Helper

Availability: View only

Callbacks afterDelete ( ) beforeDelete ( ) beforeFind (&qu..) afterFind (results)

beforeSave ( ) beforeValidate ( )

afterSave ( )

Callbacks beforeFilter ( ) afterFilter ( )

beforeRender ( )

Global Constants

Core Defines

ACL_CLASSNAME ACL_FILENAME AUTO_SESSION CACHE_CHECK CAKE_ADMIN CAKE_SECURITY

CAKE_SESSION_COOKIE

CAKE_SESSION_STRING

Paths

APP APP_DIR APP_PATH CACHE CAKE COMPONENTS CONFIGS CONTROLLER_TESTS CONTROLLERS CSS ELEMENTS HELPER_TESTS HELPERS

Component

INFLECTIONS JS LAYOUTS LIB_TESTS LIBS LOGS MODEL_TESTS MODELS SCRIPTS TESTS TMP VENDORS VIEWS Availability: Controller / View

CAKE_SESSION_TABLE

CAKE_SESSION_TIMEOUT

Properties

$disableStartup

COMPRESS_CSS DEBUG LOG_ERROR MAX_MD5SIZE WEBSERVICES

Callbacks

startup (&controller)

Properties $tags $base $here $action $themeWeb $view $webroot $params $data $plugin Callbacks

afterRender ( )

CAKE_SESSION_SAVE

Conventions

Class Name: MyCoolComponent

Path: app/controllers/components/my_cool.php

Conventions

Class Name: MyCoolHelper Path: app/views/helpers/my_cool.php

Webroot Configurable Paths

CORE_PATH ROOT WWW_ROOT WEBROOT_DIR

Usage

Controller: $this->MyCool->method( ); View: $this->controller->MyCool->method( );

Usage

View: $myCool->method( );

CAKE_CORE_INCLUDE_PATH

 

Download CakeSheet Pdf for complete reference.

 

PHP vs Ruby

Posted on February 22nd, 2008 in PHP, Ruby On Rails by Ashish  Tagged , , ,

PHP vs Ruby – Practical Language Differences

There are rather significant syntactical differences between PHP and Ruby. For example PHP requires semicolons at the end of lines and generally requires curly brackets to enclose blocks of code. Ruby, on the other hand, uses newline characters to denote the end of a line of code and many code constructs such as function definitions, and various loops are ended with the word “end” rather than being surrounded by curly braces. Below is an example of PHP vs Ruby syntax.

PHP Function

function say_hello($name) {
$out = "Hello $name";
return $out;
}

Ruby Function

def say_hello(name)
out = "Hello ${name}"
return out
end

In Ruby, you don’t have to specify the return line as the return value of the last evaluated line is returned automatically. There are other differences in syntax between PHP and Ruby and, in general, Ruby is more concise yet it is not cryptic. Another general note about PHP is that PHP has a very large number of “built-in” functions – many more than Ruby. The Rails framework adds some nice helper methods for formatting dates, numbers, currency, and the like. PHP, however, has a vast library of functions that can do almost anything you will need. The naming of the PHP functions and the order of the parameters they take are somewhat inconsistent, but the functions are there making PHP an amazingly complete tool set for web application development. An example of the naming inconsistency is evident in function names such as strpos() vs str_replace(). Sometimes an underscore is used to separate words and other times it’s not. While that can be annoying, it’s something you can memorize in time and it’s not a huge deal. What really matters to me is what can PHP do that Ruby can’t and vice versa.

PHP5 was first released over three years ago, July 13, 2007. Frustratingly, and for various compatibility reasons, PHP5 is just now beginning to be an available choice on shared hosting accounts. Nevertheless, my comparison is between PHP5 and Ruby. Both PHP5 and Ruby have object oriented features albeit, Ruby is more sophisticated in terms of OO constructs. But I wanted to know what the real difference is between the languages. When I begin development of my next web application, what will I notice in terms of the differences between the languages.

The Similarities Between PHP and Ruby

Before getting started, I know that PHP and Ruby have very significant syntactic differences and different people may prefer one over the other. So it may be harder to implement certain features in one language over the other. Nevertheless both languages can do almost the same things. Both languages have try/catch/throw style exception handling. Exceptions are new to PHP5 as PHP4 does not have them. Both languages can be used in an object oriented way. Ruby has more powerful object oriented features but most developers probably won’t notice a difference in a normal web application. Both languages have additional functionality that can be added through libraries. In general, when developing web applications, I have not yet run into a time when I was working with one language and hit a road block where the language I was using was not capable of expressing the functionality I needed. Sometimes things are easier in one language versus the other but both PHP and Ruby have been able to “do” the same things.

About Frameworks

You can’t talk about Ruby for web development without mentioning Rails. Rails is fantastic and makes developing web applications much easier due to all of the built-in functionality. My favorite aspect of Rails is the ActiveRecord functionality. Often times, many of the objects in my applications are virtually empty except for inheriting from ActiveRecord. Validation is a breeze with Rails and is usually one line such as:

validates_presence_of :attribte_name

The built-in error handling with error_messages_for is very helpful. If you need more flexibility with the display of error messages, there are plugins to available for that. The ability to turn email sending on and off for testing is extremely nice. Having different configuration files for live, testing, and development environments is great.

PHP has over 40 different frameworks available. I’ve spent a significant amount of time studying PHP frameworks. The most popular ones appear to by CakePHP and Symfony. Both of these frameworks are essentially Rails clones. I think Symfony is the largest, and most comprehensive of the two. My favorite PHP Framework, howevever, is CodeIgniter. It is a Model-View-Controller style framework and has a strong Rails feel to it, but it is much lighter weight. CodeIgniter has no code generators like Rails has. It does have an ActiveRecord style Database class but it is not as powerful as the ActiveRecord in Rails. It is, however, quite nice and very helpful – much better than nothing. CodeIgniter, as far as I know, does not have anything comparable to Migrations in Rails.

PHP Does Not Have Formal Namespaces

PHP does not officially support namespaces and Ruby does. So organizing your code in a PHP application is something that’s left to the developer to figure out. PHP5 has the ability to autoload classess that are undefined. It is a very useful function and one that I have used to organize my code into name spaces. I essentially name classes with underscores separating directory names. Here is my autoload function that replaces underscores with slashes to create a path to the class files that I am using.

define("PROJECT", "/path/to/project/classes/");
define("LIBRARY", "/path/to/my/main/php5/library/classes/");

function __autoload($className) {
$fileName = str_replace("_", DIRECTORY_SEPARATOR, $className) . ".php";
if(preg_match("/^ProjectName_/", $className)) {
include_once(PROJECT . $fileName);
}
else {
include_once(LIBRARY . $fileName);
}
}

I have a bunch of classes that I continually reuse in my PHP applications. The path to the root directory of my library is stored in the LIBRARY constant. Any classes I write that either extend my core library or are specific to the project I am working on get stored in the location specified by the PROJECT constant. This has been a system that works really well for me and is a good workaround for PHP not having namespaces. So PHP not having formal namespaces has not really hindered my development efforts.

Documentation

PHP kills Ruby and Rails when it comes to ease of finding, reading, and even generating documentation. The PHP website has wonderful, helpful, searchable documentation. The Rails Documentation is comprehensive but much harder to navigate and has far fewer code examples. PHPDocumentor also produces much better looking documentation that is easier to navigate than RDoc does.

Hosting Ruby (on Rails) Is Painful And Expensive

All the Ruby applications I have developed to date have used the Rails framework. So this is a comparison between hosting a PHP Application and a Ruby on Rails application. PHP has several good MVC style frameworks. My favorite is CodeIgniter and I’ll be posting an article about it soon. Using a framework or not, PHP is extremely easy to host. Locate virtually any hosting company, sign up for an account and start dropping your files on the server. I can’t say the same for Ruby on Rails.

I started off with a DreamHost account but performance and reliability were miserable. I ended up switching to a virtual dedicated server at Rimu Hosting and have been extremely please with their service. I’m running Apache 2.0 + Mongrel + ISPConfig and it’s working out nicely. But every time I want to deploy a new application I have to…

* Set up a mongrel cluster
* Configure 2 or three ports for the mongrel cluster
* Create a map file for my random load balancer
* Set up a way to restart the cluster if the server reboots
* Configure Apache to forward requests to the mongrel cluster
* Configure capistrano to deploy the application.

Fortunately capistrano handles all of the annoying tedium associated with deploying the application and restarting the server. So once capistrano is setup and working, future deployments are a breeze. Also worth noting, this assumes you have your source code in Subversion. So you have to make sure that Subversion is set up and accessible over the internet to the deployment server as well as your development machine. It is good practice to have you source code in version control and you should be doing this whether the project is PHP or Ruby. If you are not using subversion and, therefore, not using capistrano, deploy a rails application is very time consuming and frustrating. Lastly, you need ssh access to your deployment server if you are going to be using Ruby on Rails whereas PHP can be deployed entirely over FTP.

To have a reasonable and reliable hosting environment for Ruby on Rails applications, you should have a virtual private server (VPS) or a dedicated server. So that will cost you at least $50 per month. You can host multiple Rails applications on the same VPS but the RAM requirements for running the mongrel clusters will quickly catch up to you. While you could host well over 50 PHP sites running on your VPS you will only be able to have a handful of Rails applications.

Conclusion

I suspect very few people will argue that PHP is a more elegant language or is more powerful than Ruby. Frankly, Ruby is probably may favorite language that I have ever worked with and I have worked with Classic ASP, ASP.NET, VB.NET, C#, Java, and Perl all rather extensively over the years. Ruby is both highly expressive and concise which is rare and refreshing.

Rails is a very comprehensive and effective web development Framework and there’s nothing exactly like it in PHP. You get a huge amount of functionality for free. Developing in Ruby on Rails is also a very fast process because Ruby is a very concise language requiring much less typing than any other language I’ve worked with. CodeIgniter is a really nice PHP framework. It will give you a great boost when developing your next PHP application.

The hosting and deployment struggles with Ruby on Rails is a major sticking point for me though. As the owner of a web development company many of our smaller clients do not have the budget for their own VPS account and even if they did, we don’t have the staff to manage a large number of VPS accounts or dedicated servers. Keeping the security updates current, managing any issues that may occur with email, and all the other headaches that go along with managing your own VPS or Dedicated server is more than we care to take on for the relatively small, practical dfference between PHP and Ruby. For large projects, it may be worth the trouble, but for small to medium sized projects, PHP is much easier to deploy, less expensive to host, and the language is capable of taking on everything those types of sites require. For our projects, development time with PHP is not noticeably longer than with Ruby on Rails. Ruby on Rails integrates a lot of things for the developer.

There is ActiveRecord for managing the link between models and the database, migrations for keeping development and live databases in sync, built in testing, the ajax – prototype javascript library is included, and you get a well defined file system structure. While it may not all be packaged together as well, PHP can do all of the above.

Ruby or PHP which one is for you

Posted on February 22nd, 2008 in PHP, Ruby On Rails by Ashish  Tagged , , ,

Will Ruby kill PHP?

With the recent rise in popularity of the Ruby programming language (largely driven by the excellent but not perfect web framework called Rails), I’ve noticed a little fear in the air … fear on the part of some people in the PHP community.

Will Ruby kill PHP?

The short answer is: NO.

MY REASONING

Though Ruby and PHP are both scripting languages that make developing web applications much easier than it is, say in the Java world, they are very different beasts … each appeals to a different audience.

RUBY IS ELEGENT BUT COMPLEX

Before I go on, I want to point out that Ruby is a great language and I think it makes perfect sense for PHP developers to learn a little Ruby: it is always a good idea to learn other languages because it will make you a better programmer.

That said, I believe Ruby will not appeal to, or fill the need of most PHP’ers – Ruby can be a little too abstract.

JAVA NERDS LOVE RUBY

Ruby is attracting many from the Java world because it expresses very advanced concepts in a simple syntax – contrast this to Java’s (often times) kludgy and verbose representation.

Ruby appeals to the Java crowd because Java people have been trained to think in terms of large scale enterprise applications – regardless of the size of the project.

… These ‘abstractions’ (generally speaking) lend themselves well to larger projects.

WHY PHP WORKS

PHP is often criticized because it has both a procedural and an object oriented way of doing things. Some people think that this divergence (within the language), takes away from it … I think this is part of its strength!

Objected oriented constructs are great for creating cleaner designs that are easier to maintain and promote the possibility of code reusability. Code reuseability is an often touted advantage of OOP, but from what I’ve seen in the Java world, it is not achieved so often.

With OOP, there is a cost of added complexity and overhead – you simply have to write more code to do things when you do it via OOP.

PHP PROVES THAT NON OO LANGUAGES STILL HAVE THEIR PLACE

I would suggest that the vast majority of PHP work is found in simple projects:

* Email from a web page.
* Process a simple form and save to a database.
* Create a simple store with 10 items.

My point is, that for many PHP projects, OOP may be a little overkill.

WHY RUBY WILL NOT KILL PHP

In Ruby everything is an object (even numbers!) and the core language has very sophisticated constructs that need to be understood to use Ruby effectively – Ruby strength is also its’ weakness.

… I don’t see the majority of PHP users wanting to jump that deep into the world of programmatic abstraction – for most, there is simply no point.

Ruby is a very clean language and it has lots of things going for it. But PHP has lots of things going for it too. You can point out spots where Ruby code is cleaner than PHP, but you can point out spots where (I think) PHP code is cleaner than Ruby …

Today I would consider PHP the better choice because it is well established (lots of IDEs, open source projects, easy hosting etc ..) and proven.

Ruby is just starting to get into the mainstream … and there are still some fundamental issues with Ruby and web development.

For example: Ruby integration with APACHE is still not stable. It works … but there are known problems and can be a hassle to set up.

Ruby has a long way to go, I can’t argue for the programming details as I still like my Perl but from the SysAdmin side Ruby and Rails for the matter are an absolute nightmare.

Ruby in itself is slow, doesn’t understand threads like every other language out there so it doesn’t integrate into apache like PHP or Perl or Python or the other hundreds of web scripting languages.

Until Mongrel came out you were forced to use fast_cgi, which is a dead method of rendering pages, apache’s mod_fcgi is crap and lighttpd’s fcgi is better but the server itself is not stable enough for production.

Ruby has to start by modernizing it’s preprocessor before it even has a small chance in hell of overtaking PHP and even then Rails has a long way to go before it’s ready for the primetime, the ease at which a programmer can cause Rails to leak memory is astounding.

By: Stefan Mischook in Killersite.com

CakePHP an Open Source PHP Framework

Posted on February 18th, 2008 in Frameworks by Ashish  Tagged , , ,

CakePHP is a free open-source rapid development framework for PHP. Its a structure of libraries, classes and run-time infrastructure for programmers creating web applications originally inspired by the Ruby on Rails framework. Primary goal is to enable developers to work in a structured and rapid manner – without loss of flexibility.

In 2005, Michal Tatarynowicz wrote a minimal version of a Rapid Application Framework in PHP. He found that it was the start of a very good framework. Michal published the framework under the MIT license, dubbing it Cake, and opened it up to a community of developers, who now maintain Cake under the name CakePHP.

Features of CakePHP

CakePHP has several features that make it a great choice as a framework for developing applications swiftly and with the least amount of hassle. Here are a few in no particular order:

1. Active, friendly community
2. Flexible Licensing
3. Compatibility with PHP4 and PHP5
4. Integrated CRUD for database interaction and simplified queries
5. Application Scaffolding
6. Model View Controller (MVC) Architecture
7. Request dispatcher with good looking, custom URLs
8. Built-in Validation
9. Fast and flexible templating (PHP syntax, with helpers)
10. View Helpers for AJAX, Javascript, HTML Forms and more
11. Security, Session, and Request Handling Components
12. Flexible access control lists
13. Data Sanitization
14. Flexible View Caching
15. Works from any web site subdirectory, with little to no Apache configuration involved

Requirements

In order use CakePHP you must first have a server that has all the required libraries and programs to run CakePHP:
Server Requirements

Here are the requirements for setting up a server to run CakePHP:

1. An HTTP server (like Apache) with the following enabled: sessions, mod_rewrite (not absolutely necessary but preferred)
2. PHP 4.3.2 or greater. Yes, CakePHP works great in either PHP 4 or 5.
3. A database engine (right now, there is support for MySQL 4+, PostgreSQL and a wrapper for ADODB).

Installing CakePHP : Getting the most recent stable version

There are a few ways you can secure a copy of CakePHP: getting a stable release from CakeForge, grabbing a nightly build, or getting a fresh version of code from SVN.

To download a stable version of code, check out the files section of the CakePHP project at CakeForge by going to http://cakeforge.org/projects/cakephp/.

To grab a nightly, download one from http://cakephp.org/downloads/index/nightly. These nightly releases are stable, and often include the bug fixes between stable releases.

To grab a fresh copy from our SVN repository, use your favorite SVN client and connect to https://svn.cakephp.org/repo/trunk/cake/ and choose the version you’re after.

Unpacking

Once you’ve downloaded the most recent release, place that compressed package on your web server in the webroot. Now you need to unpack the CakePHP package. There are two ways to do this, using a development setup, which allows you to easily view many CakePHP applications under a single domain, or using the production setup, which allows for a single CakePHP application on the domain.

Setting Up CakePHP

The first way to setup CakePHP is generally only recommended for development environments because it is less secure. The second way is considered more secure and should be used in a production environment.

NOTE: /app/tmp must be writable by the user that your web server runs as.

Development Setup

For development we can place the whole Cake installation directory inside the specified DocumentRoot like this:

/wwwroot
/cake
/app
/cake
/vendors
.htaccess
index.php

In this setup the wwwroot folder acts as the web root so your URLs will look something like this (if you’re also using mod_rewrite):

www.example.com/cake/controllerName/actionName/param1/param2

Production Setup

In order to utilize a production setup, you will need to have the rights to change the DocumentRoot on your server. Doing so, makes the whole domain act as a single CakePHP application.

The production setup uses the following layout:

../path_to_cake_install
/app
/config
/controllers
/models
/plugins
/tmp
/vendors
/views
/webroot <– This should be your new DocumentRoot
.htaccess
index.php
/cake
/vendors
.htaccess
index.php

Suggested Production httpd.conf

DocumentRoot /path_to_cake/app/webroot

In this setup the webroot directory is acting as the web root so your URLs might look like this (if you’re using mod_rewrite):

http://www.example.com/controllerName/actionName/param1/param2

Advanced Setup: Alternative Installation Options

There are some cases where you may wish to place Cake’s directories on different places on disk. This may be due to a shared host restriction, or maybe you just want a few of your apps to share the same Cake libraries.

There are three main parts to a Cake application:

1. The core CakePHP libraries – Found in /cake
2. Your application code (e.g. controllers, models, layouts and views) – Found in /app
3. Your application webroot files (e.g. images, javascript and css) – Found in /app/webroot

Each of these directories can be located anywhere on your file system, with the exception of the webroot, which needs to be accessible by your web server. You can even move the webroot folder out of the app folder as long as you tell Cake where you’ve put it.

To configure your Cake installation, you’ll need to make some changes to /app/webroot/index.php (as it is distributed in Cake). There are three constants that you’ll need to edit: ROOT, APP_DIR, and CAKE_CORE_INCLUDE_PATH.

1. ROOT should be set to the path of the directory that contains your app folder.
2. APP_DIR should be set to the path of your app folder.
3. CAKE_CORE_INCLUDE_PATH should be set to the path of your Cake libraries folder.

/app/webroot/index.php (partial, comments removed)
if (!defined(’ROOT’))
{
define(’ROOT’, dirname(dirname(dirname(__FILE__))));
}

if (!defined(’APP_DIR’))
{
define (’APP_DIR’, basename(dirname(dirname(__FILE__))));
}

if (!defined(’CAKE_CORE_INCLUDE_PATH’))
{
define(’CAKE_CORE_INCLUDE_PATH’, ROOT);
}

An example might help illustrate this better. Imagine that I wanted to set up Cake to work with the following setup:

1. I want my Cake libraries shared with other applications, and placed in /usr/lib/cake.
2. My Cake webroot directory needs to be /var/www/mysite/.
3. My application files will be stored in /home/me/mysite.

Here’s what the file setup looks like:

/home
  /me
   /mysite <– Used to be /cake_install/app
      /config
      /controllers
      /models
      /plugins
      /tmp
      /vendors
      /views
      index.php

/var
   /www
     /mysite <– Used to be /cake_install/app/webroot
       /css
       /files
       /img
       /js
       .htaccess
        css.php
        favicon.ico
        index.php

/usr
    /lib
        /cake <– Used to be /cake_install/cake
            /cake
                /config
                /docs
                /libs
                /scripts
                app_controller.php
                app_model.php
                basics.php
                bootstrap.php
                dispatcher.php
                /vendors

Given this type of setup, I would need to edit my webroot index.php file (which should be at /var/www/mysite/index.php, in this example) to look like the following:

It is recommended to use the ‘DS’ constant rather than slashes to delimit file paths. This prevents any ‘missing file’ errors you might get as a result of using the wrong delimiter, and it makes your code more portable.
if (!defined(’ROOT’))
{
define(’ROOT’, DS.’home’.DS.’me’);
}

if (!defined(’APP_DIR’))
{
define (’APP_DIR’, ‘mysite’);
}

if (!defined(’CAKE_CORE_INCLUDE_PATH’))
{
define(’CAKE_CORE_INCLUDE_PATH’, DS.’usr’.DS.’lib’.DS.’cake’);
}

Configuring Apache and mod_rewrite

While CakePHP is built to work with mod_rewrite out of the box, we’ve noticed that a few users struggle with getting everything to play nicely on their systems. Here are a few things you might try to get it running correctly:

1. Make sure that an .htaccess override is allowed: in your httpd.conf, you should have a section that defines a section for each Directory on your server. Make sure the AllowOverride is set to All for the correct Directory.
2. Make sure you are editing the system httpd.conf rather than a user- or site-specific httpd.conf.
3. For some reason or another, you might have obtained a copy of CakePHP without the needed .htaccess files. This sometimes happens because some operating systems treat files that start with ‘.’ as hidden, and don’t copy them. Make sure your copy of CakePHP is from the downloads section of the site or our SVN repository.
4. Make sure you are loading up mod_rewrite correctly! You should see something like LoadModule rewrite_module libexec/httpd/mod_rewrite.so and AddModule mod_rewrite.c in your httpd.conf.
5. If you are installing Cake into a user directory (http://example.com/~myusername/), you’ll need to modify the .htaccess files in the base directory of your Cake installation, and in the app/webroot folder. Just add the line "RewriteBase /~myusername/".
6. If for some reason your URLS are suffixed with a long, annoying session ID (http://example.com/posts/?CAKEPHP=4kgj577sgabvnmhjgkdiuy1956if6ska), you might also add "php_flag session.trans_id off" to the .htaccess file at the root of your installation as well.

Database Configuration

Your app/config/database.php file is where your database configuration all takes place. A fresh install doesn’t have a database.php, so you’ll need to make a copy of database.php.default. Once you’ve made a copy and renamed it you’ll see the following:

app/config/database.php

var $default = array(’driver’ => ‘mysql’,
‘connect’ => ‘mysql_connect’,
‘host’ => ‘localhost’,
‘login’ => ‘user’,
‘password’ => ‘password’,
‘database’ => ‘project_name’,
‘prefix’ => ”);

Replace the information provided by default with the database connection information for your application.

One note about the prefix key: the string you enter there will be prepended to any SQL call that Cake makes to your database when working with tables. You define it here once so you don’t have to specify it in other places. It also allows you to follow Cake’s table naming conventions if you’re on a host that only gives you a single database. Note: for HABTM join tables, you only add the prefix once: prefix_apples_bananas, not prefix_apples_prefix_bananas.

CakePHP supports the following database drivers:

1. mysql
2. postgres
3. sqlite
4. pear-drivername (so you might enter pear-mysql, for example)
5. adodb-drivername

The ‘connect’ key in the $default connection allows you to specify whether or not the database connection will be treated as persistent or not. Read the comments in the database.php.default file for help on specifying connection types for your database setup.

Your database tables should also follow the following conventions:

1. Table names used by Cake should consist of English words in plural, like "users", "authors" or "articles". Note that corresponding models have singular names.
2. Your tables must have a primary key named ‘id’.
3. If you plan to relate tables, use foreign keys that look like: ‘article_id’. The table name is singular, followed by an underscore, followed by ‘id’.
4. If you include a ‘created’ and/or ‘modified’ column in your table, Cake will automatically populate the field when appropriate.

You’ll also notice that there is a $test connection setting included in the database.php file. Fill out this configuration (or add other similarly formatted configurations) and use it in your application by placing something like:
var $useDbConfig = ‘test’;

Inside one of your models. You can add any number of additional connection settings in this manner.

Global Configuration

CakePHP’s global configuration can be found in app/config/core.php. While we really dislike configuration files, it just had to be done. There are a few things you can change here, and the notes on each of these settings can be found within the comments of the core.php file.

DEBUG: Set this to different values to help you debug your application as you build it. Specifying this setting to a non-zero value will force Cake to print out the results of pr( ) and debug( ) function calls, and stop flash messages from forwarding automatically. Setting it to 2 or higher will result in SQL statements being printed at the bottom of the page.

Also when in debug mode (where DEBUG is set to 1 or higher), Cake will render certain generated error pages, i.e. "Missing Controller," "Missing Action," etc. In production mode, however (where DEBUG is set to 0), Cake renders the "Not Found" page, which can be overridden in app/views/errors/error404.thtml.

CAKE_SESSION_COOKIE: Change this value to the name of the cookie you’d like to use for user sessions in your Cake app.

CAKE_SECURITY: Change this value to indicate your preferred level of sessions checking. Cake will timeout sessions, generate new session ids, and delete old session files based on the settings you provide here. The possible values are:

1. high: sessions time out after 20 minutes of inactivity, and session id’s are regenerated on each request
2. medium: sessions time out after 200 minutes of inactivity
3. low: sessions time out after 600 minutes of inactivity

CAKE_SESSION_SAVE: Specify how you’d like session data saved. Possible values are:

1. cake: Session data is saved in tmp/ inside your Cake installation
2. php: Session data saved as defined in php.ini
3. database: Session data saved to database connection defined by the ‘default’ key.

Routes Configuration

"Routing" is a pared-down pure-PHP mod_rewrite-alike that can map URLs to controller/action/params and back. It was added to Cake to make pretty URLs more configurable and to divorce us from the mod_rewrite requirement. Using mod_rewrite, however, will make your address bar look much more tidy.

Routes are individual rules that map matching URLs to specific controllers and actions. Routes are configured in the app/config/routes.php file. They are set-up like this:

Route Pattern
<?php
$Route->connect (
‘URL’,
array(’controller’=>’controllername’,
‘action’=>’actionname’, ‘firstparam’)
);
?>

Where:

1. URL is the regular expression Cake URL you wish to map,
2. controllername is the name of the controller you wish to invoke,
3. actionname is the name of the controller’s action you wish to invoke,
4. and firstparam is the value of the first parameter of the action you’ve specified.

Any parameters following firstparam will also be passed as parameters to the controller action.

php.MVC is an open source framework for PHP Web applications

Posted on February 18th, 2008 in Frameworks by Ashish  Tagged , , ,

php.MVC implements the Model-View-Controller (MVC) design pattern, and encourages application design based on the Model 2 paradigm. This design model allows the Web page or other contents (View) to be mostly separated from the internal application code (Controller/Model), making it easier for designers and programmers to focus on their respective areas of expertise.

The framework provides a single entry point Controller. The Controller is responsible for allocating HTTP requests to the appropriate Action handler (Model) based on configuration mappings.

The Model contains the business logic for the application. The Controller then forwards the request to the appropriate View component, which is usually implemented using a combination of HTML with PHP tags in the form of templates. The resulting contents are returned to the client browser, or via another protocol such as SMTP.

php.MVC is a PHP port of Jakarta Struts. It currently supports many features of Struts, including declarative application configuration via the XML digester.

Key Features of php.MVC

• Free OpenSource software: This gives users full control of the software, and the able to modify the source code to suit specific needs.

• Security: php.MVC applications have only one entry point (per application). This makes it easy to protect sensitive application code and data.

• Flexible Installation: Individual php.MVC applications can be installed outside of the main php.MVC library directory tree.

• Multi-applications: There is no limit to the number of applications per php.MVC installation.

• Object Oriented design (OOD). The php.MVC framework is based on OOD principles, making it more extendable and maintainable.

• Database integration: The php.MVC framework ships with the Pear::DB Database Abstraction Layer, and a driver for the MySQL relational database manager (RDBM) is provided.

• Action Chaining: php.MVC allows for passing control to other Actions. This makes it easy to process a sequence of Actions (business logic classes) and static resources (pages).

• XML configuration: php.MVC uses declarative application configurations using Extensible Markup Language (XML) files. Each application has its own XML configuration file.

• MVC Model 2 design: php.MVC implements the Model-View-Controller (MVC) Model 2 design pattern. The Model 2 paradigm allows the separation of the application presentation from the business logic, making it easier for designers and programmers to focus on their respective areas of expertise.

• Form button mapping: php.MVC implements the LookupDispatchAction class to enable HTML form buttons to be mapped to particular business logic methods. For example, a form submit button called "Add to Cart" could be mapped to an Action class method called MyCartAction->addToCart(…).

• Message Resources: php.MVC provides a PropertyMessageResources class that handles messages in text string properties files with parametric replacement. This can provide Locale-sensitive messages for internationalized applications.

• The php.MVC framework is based on Jakarta Struts application framework design. Struts has proven to be reliable, extendable and well supported.

Requirements

• PHP enabled Web server

• PHP v. 4.1.0 or greater

• XML parser (James Clark’s expat is usually included with most PHP versions)

Installation

MS Windows Installation

1) Copy the phpmvc-beta-xxx.zip archive to the Web server (SCP/FTP)

2) Unpack the tarball zip

• SSH to the Web server

• Change to the directory where phpmvc will live. Eg: C:\WWW\

• Backup/move any existing phpmvc directory. Eg: C:\WWW\phpmvc-BAK

• Unzip the phpmvc-beta-xxx.zip archive to the target directory.
Eg: C:\WWW\phpmvc

• Remove the phpmvc-beta-xxx.zip tarball [optional]

3) Setup the Simple Example application

• Move into the main phpmvc directory. Eg: C:\WWW\phpmvc

• Set the Simple Example application root and module directory in Main.php
Note: These paths are absolute file-system paths.
Note: In this case the paths are the same as Simple Example Main.php file is in the php.MVC root directory.

/* ———- Application Paths ———- */
// Set php.MVC library root directory
$appServerRootDir = ‘C:/WWW/phpmvc’; // no trailing slash

// Set the application path
$moduleRootDir = ‘C:/WWW/phpmvc’; // no trailing slash
/* ———- Application Paths ———- */

• Enable write permission on the WEB-INF/phpmvc-config.data file.
Note: The Web server must have write permission on WEB- INF/phpmvc-config.data file
Note: The WEB-INF/* directory tree should be accessable ONLY by localhost per .htaccess file
Note: If you have admin access to the server, change the phpmvc-config.data file to be writable
by the Web server group for added security.

4) Setup the OOHForms demo module

• Move into the OOHForms demo module directory. Eg: C:\WWW\phpmvc\oohforms

• Set the OOHForms demo application root and module directory in Main.php
Note: These paths are absolute file-system paths.

/* ———- Application Paths ———- */
// Set php.MVC library root directory
$appServerRootDir = ‘C:/WWW/phpmvc’; // no trailing slash

// Set the application path
$moduleRootDir = ‘C:/WWW/phpmvc/oohforms’; // no trailing slash
/* ———- Application Paths ———- */

• Enable write permission on the WEB-INF/phpmvc-config.data file for this application.
Note: As above

5) Test Web access to WEB-INF/*

• There should be NO access or directory listing to WEB-INF/* in the main or sub application.

6) Test the basic php.MVC framework demos

• The Simple Example:
Browse to your install directory, with the path "do=stdLogon".
Eg: http://myserver.com/phpmvc/Main.php?do=stdLogon

• The OOHForms demo:
Browse to the phpmvc/oohforms/index.php file and follow the links.

7) Troubleshooting

• If all you get is file path errors, please try setting the $osType variable in the Main.php files to the correct server OS.
Eg: $osType = ‘WINDOWS’;

Linux (Redhat) Installation

1) Copy phpmvc-beta-xxx.tgz to the Web server (FTP)

2) Unpack the tarball

• SSH to the Web server

• Change to the directory where phpmvc will live.
bash$ cd www

• Backup/move any existing phpmvc directory
bash$ mv phpmvc phpmvc-BAK

• Create the phmmvc directory and unpack archive
bash$ tar xvzf phpmvc-20021126.tgz

• Remove the phpmvc-beta-xxx.tgz tarball [optional]
bash$ rm phpmvc-beta-xxx.tgz

3) Setup the Simple Example application

• Move into the main phpmvc directory
bash$ cd phpmvc
Check the path to the phpmvc root directory ($appServerRootDir)
bash$ pwd (/home/myhome/www/phpmvc)

• Set the Simple Example application root and module directory in Main.php
Note: These paths are absolute file-system paths.
Note: In this case the paths are the same as Simple Example Main.php file is in the php.MVC root directory.

/* ———- Application Paths ———- */
// Set php.MVC library root directory
$appServerRootDir = ‘/home/myhome/www/phpmvc’; // no trailing slash

// Set the application path
$moduleRootDir = ‘/home/myhome/www/phpmvc’; // no trailing slash
/* ———- Application Paths ———- */

• Enable write permission on the phpmvc-config.data file.
bash$ chmod o+w WEB-INF/phpmvc-config.data (*** world writable ***)

Note: The Web server must have write permission on WEB- INF/phpmvc-config.data file
Note: The WEB-INF/* directory tree should be accessable ONLY by localhost per .htaccess file
Note: If you have root access to the server, change the phpmvc-config.data file to be writable
by the Web server group for added security.
bash$ chmod g+w WEB-INF/phpmvc-config.data
root# chgrp apachegroup WEB-INF/phpmvc-config.data

4) Setup the OOHForms demo module

• Move into the OOHForms demo module directory
bash$ cd oohforms

• Set the main application root directory in Main.php
bash$ vi Main.php

• Set the OOHForms demo application root and module directory in Main.php

/* ———- Application Paths ———- */
// Set php.MVC library root directory
$appServerRootDir = ‘/home/myhome/www/phpmvc’; // no trailing slash

// Set the application path
$moduleRootDir = ‘/home/myhome/www/phpmvc/oohforms’; // no trailing slash
/* ———- Application Paths ———- */

• Enable write permission on the phpmvc-config.data file
bash$ chmod o+w WEB-INF/phpmvc-config.data (*** world writable ***)
Notes: As above

5) Test Web access to WEB-INF/*

• There should be NO access or directory listing to WEB-INF/* in the main or sub application.

6) Test the basic php.MVC framework demos

• The Simple Example:
Browse to your install directory, with the path "do=stdLogon".
Eg: http://myserver.com/phpmvc/Main.php?do=stdLogon

• The OOHForms demo:
Browse to the phpmvc/oohforms/index.php file and follow the links.

7) Troubleshooting

• If all you get is file path errors, please try setting the $osType variable in the Main.php files to the correct server OS.
Eg: $osType = ‘UNIX’;

User Guides can be found here:

http://www.phpmvc.net/docs/guides/guidesIdx.php

You Can download php.MVC from here

http://www.phpmvc.net/download/downloadIdx.php?doc=phpmvc-docs

 

The World’s Most Misunderstood Programming Language

Posted on February 12th, 2008 in JavaScript by Ashish  Tagged , , ,

JavaScript, aka Mocha, aka LiveScript, aka JScript, aka ECMAScript, is one of the world’s most popular programming languages. Virtually every personal computer in the world has at least one JavaScript interpreter installed on it and in active use. JavaScript’s popularity is due entirely to its role as the scripting language of the WWW.

Despite its popularity, few know that JavaScript is a very nice dynamic object-oriented general-purpose programming language. How can this be a secret? Why is this language so misunderstood?

The article by Douglas in Crockford.com clearly shows the lack of knowledge or misunderstanding people have about JavaScript.

I do believe that there can be several reasons why people haven’t taken the JavaScript as strongly as they took other server side languages like PHP, Ruby etc though JS is used in almost all the websites.

The problem of JavaScript is that for years there have been no decent debugging tools. Because of that it takes a huge amount of effort just to write stable code. At the end the day a programmer is so frustrated with JavaScript that at the point he’s not interested in looking into ‘cool’ features.

I think it’s libraries like Prototype, script.aculo.us, etc. that have breathed new life in to JavaScript. At any rate, they caused me to take a second look at the language and realize its power and usefulness.

I would highly recommend Dojo, http://dojotoolkit.org/, to anyone thinking of doing any type of semi-complex javascript or AJAX. It also has scads of utility scripts that, in the past, I have found myself writing over and over again.

Though the docs are currently sparse, there a large number of test cases that give great examples and the mailing list is incredibly helpful. Dojo is also great example of how to properly write OO javascript. They even use a package naming structure similar to Java to help organize code.

I have also found few people in my vicinity who thinks that COBOL is most misunderstood programming language.

How much you know about JavaScript

Posted on February 12th, 2008 in JavaScript by Ashish  Tagged , , ,

Think you know all about JavaScript? Well Read On..

JavaScript is a scripting language most often used for client-side web development. It was the originating dialect of the ECMAScript standard. As such, it is a dynamic, weakly typed, prototype-based language with first-class functions.

JavaScript was influenced by many languages and was designed to have a similar look to Java, but be easier for non-programmers to work with. The language is best known for its use in websites (as client-side JavaScript), but is also used to enable scripting access to objects embedded in other applications.

Despite the name, JavaScript is essentially unrelated to the Java programming language, though both have a common debt to C syntax, and JavaScript copies many Java names and naming conventions. The language was renamed from LiveScript in a co-marketing deal between Netscape and Sun in exchange for Netscape bundling Sun’s Java runtime with their browser, which was dominant at the time. The key design principles within JavaScript are inherited from the Self programming language.

"JavaScript" is a trademark of Sun Microsystems. It was used under license for technology invented and implemented by Netscape Communications and current entities such as the Mozilla Foundation.

avaScript was originally developed by Brendan Eich of Netscape under the name Mocha, later LiveScript, and finally renamed to JavaScript. The change of name from LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. JavaScript was first introduced and deployed in the Netscape browser version 2.0B3 in December of 1995. The naming has caused confusion, giving the impression that the language is a spinoff of Java and has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language.

To avoid trademark issues, Microsoft named its dialect of the language JScript. JScript was first supported in Internet Explorer version 3.0, released in August 1996 and included Y2K compliant date functions, unlike those based on java.util.Date in JavaScript at the time.

Netscape submitted JavaScript to Ecma International for standardization resulting in the standardized version named ECMAScript.

JavaScript Features

Structured programming

JavaScript supports all the structured programming syntax in C, e.g. if statement, while loops, switch statement, etc. One exception is scoping: JavaScript supports function-level scoping, but not block-level scoping.

Dynamic programming

dynamic typing
As in most scripting languages, types are associated with values, not variables. For example, a variable x could be bound to a number, then later rebound to a string. JavaScript supports various ways to test the type of an object, including duck typing.
objects as associative arrays
JavaScript is heavily object-based. Objects are associative arrays, such that object property names are associative array keys. obj.x = 10 and obj["x"] = 10 are equivalent, the dot notation being merely syntactic sugar. Properties and their values can be added, changed, or deleted at run-time.
interpreted
Conforming JavaScript engines must be able to interpret (as opposed to compile) source code. This allows JavaScript to include an eval function.

Function-level programming

first-class functions
Functions are first-class; they are objects themselves. As such, they have properties and can be passed around and interacted with like any other object.
inner functions and closures
Inner functions (functions defined within other functions) are created each time the outer function is invoked, and variables of the outer functions for that invocation continue to exist as long as the inner functions still exist, even if that invocation is finished (e.g. if the inner function was returned) — this is the mechanism behind closures within JavaScript.

Prototype-based

prototypes
JavaScript uses prototypes instead of classes for defining object properties, including methods, and inheritance. It is possible to simulate many class-based features with prototypes in JavaScript.
functions as object constructors
Functions double as object constructors along with their typical role. Prefixing a function call with new creates a new object and calls that function with its local this keyword bound to that object. The function’s prototype property determines the new object’s prototype.
functions as methods
Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; a function can be called as a method. When a function is invoked as a method of an object, the function’s local this keyword is bound to that object.

Others

run-time environment
JavaScript typically relies on a run-time environment (e.g. in a web browser) to provide objects and methods by which scripts can interact with "the outside world". (This is not a language feature per se, but it is common in most JavaScript implementations.)
variadic functions
An indefinite number of parameters can be passed to a function. The function can both access them through formal parameters and the local arguments object.
regular expressions
JavaScript also supports regular expressions in a manner similar to Perl, which provide a concise and powerful syntax for text manipulation that is more sophisticated than the built-in string functions.

Use in Web pages

The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page. Some simple examples of this usage are:

* Opening or popping up a new window with programmatic control over the size, position and ‘look’ of the new window (i.e. whether the menus, toolbars, etc. are visible).
* Validation of web form input values to make sure that they will be accepted before they are submitted to the server.
* Changing images as the mouse cursor moves over them: This effect is often used to draw the user’s attention to important links displayed as graphical elements.

Because JavaScript code can run locally in a user’s browser (rather than on a remote server), it can respond to user actions quickly, making an application feel more responsive. Furthermore, JavaScript code can detect user actions which HTML alone cannot, such as individual keystrokes. Applications such as Gmail take advantage of this: much of the user-interface logic is written in JavaScript, and JavaScript dispatches requests for information (such as the content of an e-mail message) to the server. The wider trend of Ajax programming similarly exploits this strength.

A JavaScript engine (also known as JavaScript interpreter or JavaScript implementation) is an interpreter that interprets JavaScript source code and executes the script accordingly. The first ever JavaScript engine was created by Brendan Eich at Netscape Communications Corporation, for the Netscape Navigator web browser. The engine, code named SpiderMonkey, is implemented in C. It has since been updated (in JavaScript 1.5) to conform to ECMA-262 Edition 3. The Rhino engine, created primarily by Norris Boyd (also at Netscape) is a JavaScript implementation in Java. Like SpiderMonkey, Rhino is ECMA-262 Edition 3 compliant.

By far, the most common host environment for JavaScript is a web browser. Web browsers typically use the public API to create "host objects" responsible for reflecting the DOM into JavaScript. The web server is another common application of the engine. A JavaScript webserver would expose host objects representing a HTTP request and response objects, which a JavaScript program could then manipulate to dynamically generate web pages.

JavaScript Compatibility considerations

The DOM interfaces for manipulating Web pages are not part of the ECMAScript standard, or of JavaScript itself. Officially, they are defined by a separate standardization effort by the W3C; in practice, browser implementations differ from the standards and from each other, and not all browsers execute JavaScript.

To deal with these differences, JavaScript authors can attempt to write standards-compliant code which will also be executed correctly by most browsers; failing that, they can write code that checks for the presence of certain browser features and behaves differently if they are not available. In some cases, two browsers may both implement a feature but with different behavior, and authors may find it practical to detect what browser is running and change their script’s behavior to match. Programmers may also use libraries or toolkits which take browser differences into account.

Furthermore, scripts will not work for all users. For example, a user may:

* use an old or rare browser with incomplete or unusual DOM support,
* use a PDA or mobile phone browser which cannot execute JavaScript,
* have JavaScript execution disabled as a security precaution,
* or be visually or otherwise disabled and use a speech browser

To support these users, Web authors can try to create pages which degrade gracefully on user agents (browsers) which do not support the page’s JavaScript.

Security

JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the Web. Browser authors contain this risk using two restrictions. First, scripts run in a sandbox in which they can only perform Web-related actions, not general-purpose programming tasks like creating files. Second, scripts are constrained by the same origin policy: scripts from one Web site do not have access to information such as usernames, passwords, or cookies sent to another site. Most JavaScript-related security bugs are breaches of either the same origin policy or the sandbox.

Cross-site vulnerabilities

A common JavaScript-related security problem is cross-site scripting, or XSS, a violation of the same origin policy. XSS vulnerabilities occur when an attacker is able to cause a trusted Web site, such as an online banking website, to include a malicious script in the webpage presented to a victim. In that example, the script can then access the banking application with the privileges of the victim, potentially disclosing secret information or transferring money without the victim’s authorization.

XSS vulnerabilities can also occur because of implementation mistakes by browser authors.

XSS is related to, but not the same as, cross-site request forgery or XSRF. In XSRF, one website causes a victim’s browser to generate fraudulent requests to another site, with the victim’s legitimate HTTP cookies attached to the request.

Misunderstanding the client-server boundary

Client-server applications, whether they involve JavaScript or not, must assume that untrusted clients may be under the control of attackers. Thus any secret embedded in JavaScript could be extracted by a determined adversary, and the output of JavaScript operations should not be trusted by the server. Some implications:

* Web site authors cannot perfectly conceal how their JavaScript operates because the code is sent to the client and obfuscated code can be reverse engineered.
* JavaScript form validation only provides convenience for users, not security. If a site verifies that the user agreed to its terms of service, or filters invalid characters out of fields that should only contain numbers, it must do so on the server, not only the client.
* It would be extremely bad practice to embed a password in JavaScript (where it can be extracted by an attacker), then have JavaScript verify a user’s password and pass "password_ok=1" back to the server (since the "password_ok=1" response is easy to forge).

Browser and plugin coding errors

JavaScript provides an interface to a wide range of browser capabilities, some of which may have flaws such as buffer overflows. These flaws can allow attackers to write scripts which would run any code they wish on the user’s system.

These flaws have affected major browsers including Firefox, Internet Explorer, and Safari.

Plugins, such as video players, Macromedia Flash, and the wide range of ActiveX controls enabled by default in Microsoft Internet Explorer, may also have flaws exploitable via JavaScript, and such flaws have been exploited in the past. In Windows Vista, Microsoft has attempted to contain the risks of bugs such as buffer overflows by running the Internet Explorer process with limited privileges.

Sandbox implementation errors

Web browsers are capable of running JavaScript outside of the sandbox, with the privileges necessary to, for example, create or delete files. Of course, such privileges aren’t meant to be granted to code from the Web.

Incorrectly granting privileges to JavaScript from the Web has played a role in vulnerabilities in both Internet Explorer and Firefox. In Windows XP Service Pack 2, Microsoft tightened the rules on what JavaScript would be run with high privileges by Internet Explorer.

Some versions of Microsoft Windows allow JavaScript stored on a computer’s hard drive to run as a general-purpose, non-sandboxed program. This makes JavaScript (like VBScript) a theoretically viable vector for a Trojan horse, although JavaScript Trojan horses are uncommon in practice.

Meta Tags and Basics

Posted on January 31st, 2008 in SEO by Ashish  Tagged , ,

Developers should learn the basics of Meta Tags : Scott Clark

Contributed on Webdeveloper.com

With all the new HTML tags that are coming out, it’s easy to overlook some of the greatest tools in our arsenal of HTML tricks. There are still a few HTML goodies lying around that’ll help you keep your pages more up to date, make them easier to find, and even stop them from becoming framed. What’s more, some of these tags have been with us since the first Web browsers were released.

META tags can be very useful for Web developers. They can be used to identify the creator of the page, what HTML specs the page follows, the keywords and description of the page, and the refresh parameter (which can be used to cause the page to reload itself, or to load another page). And these are just a few of the common uses!

First, there are two types of META tags: HTTP-EQUIV and META tags with a NAME attribute.

HTTP-EQUIV
META HTTP-EQUIV tags are the equivalent of HTTP headers. To understand what headers are, you need to know a little about what actually goes on when you use your Web browser to request a document from a Web server. When you click on a link for a page, the Web server receives your browser’s request via HTTP. Once the Web server has made sure that the page you’ve requested is indeed there, it generates an HTTP response. The initial data in that response is called the "HTTP header block." The header tells the Web browser information which may be useful for displaying this particular document

Back to META tags. Just like normal headers, META HTTP-EQUIV tags usually control or direct the actions of Web browsers, and are used to further refine the information which is provided by the actual headers. HTTP-EQUIV tags are designed to affect the Web browser in the same manner as normal headers. Certain Web servers may translate META HTTP-EQUIV tags into actual HTTP headers automatically so that the user’s Web browser would simply see them as normal headers. Some Web servers, such as Apache and CERN httpd, use a separate text file which contains meta-data. A few Web server-generated headers, such as "Date," may not be overwritten by META tags, but most will work just fine with a standard Web server.

NAME
META tags with a NAME attribute are used for META types which do not correspond to normal HTTP headers. This is still a matter of disagreement among developers, as some search engine agents (worms and robots) interpret tags which contain the keyword attribute whether they are declared as "name" or "http-equiv," adding fuel to the fires of confusion

Using META Tags

On to more important issues, like how to actually implement META tags in your Web pages. If you’ve ever had readers tell you that they’re seeing an old version of your page when you know that you’ve updated it, you may want to make sure that their browser isn’t caching the Web pages. Using META tags, you can tell the browser not to cache files, and/or when to request a newer version of the page. In this article, we’ll cover some of the META tags, their uses, and how to implement them.

Expires
This tells the browser the date and time when the document will be considered "expired." If a user is using Netscape Navigator, a request for a document whose time has "expired" will initiate a new network request for the document. An illegal Expires date such as "0" is interpreted by the browser as "immediately." Dates must be in the RFC850 format, (GMT format):

Pragma
This is another way to control browser caching. To use this tag, the value must be "no-cache". When this is included in a document, it prevents Netscape Navigator from caching a page locally.

These two tags can be used as together as shown to keep your content current—but beware. Many users have reported that Microsoft’s Internet Explorer refuses the META tag instructions, and caches the files anyway. So far, nobody has been able to supply a fix to this "bug." As of the release of MSIE 4.01, this problem still existed.

Refresh
This tag specifies the time in seconds before the Web browser reloads the document automatically. Alternatively, it can specify a different URL for the browser to load.

Be sure to remember to place quotation marks around the entire CONTENT attribute’s value, or the page will not reload at all.

Set-Cookie
This is one method of setting a "cookie" in the user’s Web browser. If you use an expiration date, the cookie is considered permanent and will be saved to disk (until it expires), otherwise it will be considered valid only for the current session and will be erased upon closing the Web browser.

Window-target
This one specifies the "named window" of the current page, and can be used to prevent a page from appearing inside another framed page. Usually this means that the Web browser will force the page to go the top frameset.

PICS-Label
Although you may not have heard of PICS-Label (PICS stands for Platform for Internet Content Selection), you probably will soon. At the same time that the Communications Decency Act was struck down, the World Wide Web Consortium (W3C) was working to develop a standard for labeling online content (see www.w3.org/PICS/ ). This standard became the Platform for Internet Content Selection (PICS). The W3C’s standard left the actual creation of labels to the "labeling services." Anything which has a URL can be labeled, and labels can be assigned in two ways. First, a third party labeling service may rate the site, and the labels are stored at the actual labeling bureau which resides on the Web server of the labeling service. The second method involves the developer or Web site host contacting a rating service, filling out the proper forms, and using the HTML META tag information that the service provides on their pages. One such free service is the PICS-Label generator that Vancouver-Webpages provides. It is based on the Vancouver Webpages Canadian PICS ratings, version 1.0, and can be used as a guideline for creating your own PICS-Label META tag.

Although PICS-Label was designed as a ratings label, it also has other uses, including code signing, privacy, and intellectual property rights management. PICS uses what is called generic and specific labels. Generic labels apply to each document whose URL begins with a specific string of characters, while specific labels apply only to a given file.

Keyword and Description attributes
Chances are that if you manually code your Web pages, you’re aware of the "keyword" and "description" attributes. These allow the search engines to easily index your page using the keywords you specifically tell it, along with a description of the site that you yourself get to write. Couldn’t be simpler, right? You use the keywords attribute to tell the search engines which keywords to use, like this:

By the way, don’t think you can spike the keywords by using the same word repeated over and over, as most search engines have refined their spiders to ignore such spam. Using the META description attribute, you add your own description for your page:

Make sure that you use several of your keywords in your description. While you are at it, you may want to include the same description enclosed in comment tags, just for the spiders that do not look at META tags. To do that, just use the regular comment tags, like this:

!–// This page is about the meaning of life, the universe, mankind and plants. //–

More about search engines can be found in our special report.

ROBOTs in the mist
On the other hand, there are probably some of you who do not wish your pages to be indexed by the spiders at all. Worse yet, you may not have access to the robots.txt file. The robots META attribute was designed with this problem in mind.
meta NAME="robots" CONTENT="all | none | index | noindex | follow | nofollow">

The default for the robot attribute is "all". This would allow all of the files to be indexed. "None" would tell the spider not to index any files, and not to follow the hyperlinks on the page to other pages. "Index" indicates that this page may be indexed by the spider, while "follow" would mean that the spider is free to follow the links from this page to other pages. The inverse is also true, thus this META tag:

meta NAME="robots" CONTENT=" noindex">

would tell the spider not to index this page, but would allow it to follow subsidiary links and index those pages. "nofollow" would allow the page itself to be indexed, but the links could not be followed. As you can see, the robots attribute can be very useful for Web developers. For more information about the robot attribute, visit the W3C’s robot paper.

Placement of META tags
META tags should always be placed in the head of the HTML document between the actual tags, before the BODY tag. This is very important with framed pages, as a lot of developers tend to forget to include them on individual framed pages. Remember, if you only use META tags on the frameset pages, you’ll be missing a large number of potential hits.

Obscure META Tags

If you’re a normal person (I’m not, and I don’t know any, but I heard they do exist), then you’re wondering just what, exactly, is Dublin Core? No, it’s not an Irish porno movie, but rather, it’s a simple resource description record that has come to be known as the Dublin Core Metadata element set, or rather, Dublin Core.

Thanks to a considerate reader, we now know how it got its name. Dublin Core is the core set of metadata elements which were identified by a working group (comprised of experts drawn from the library and Internet communities) which met in Dublin, Ohio.

Dublin Core was designed with several issues in mind, namely to:

* enable search engines to filter by standard fields, i.e. date and author
* Browsers could have the ability to display metadata fields in a separate window
* enhance cross-collection, repurposing and integrating of content
* enhance site management, as old pages may be located more easily, etc.

Rating is basically the same thing as PICS-Label, and can be used for the same purpose, but PICS-Label is recommended over rating, as it is currently recognized by more software than rating, although it couldn’t hurt to use both.

Many of the obscure META tags are produced by HTML authoring software. Microsoft Word supports a number of META attributes in its HTML export option, and if you create a document with Internet Assistant, FrontPage, etc, you’ll notice that they automatically insert certain META tags, such as Generator, Content-Type, etc. into the Web page source. Other META tags are organization or search engine specific. The RDU Metadata search engine uses many such tags, including: contributor, custodian, east_bounding_coordinate, north_bounding_coordinate and others. Other obscurities are government META tags, useful only if you are within a government intranet or system.

But then
Statistics show that only about 21% of Web pages use keyword and description META tags. If you use them and your competitor doesn’t, that’s one in your favor. If your competitor is using them and you aren’t, you may now consider yourself armed with the knowledge. META tags are something that visitors to your Web site are usually not aware of, but ironically, a lot of times it was those same META tags which enabled them to find you in the first place. So for goodness’ sake, don’t tell anyone about this….let’s just keep this our own little secret (just kidding…make sure to send this URL to everyone you know!).

The Law
Before we leave the topic of META tags, keep in mind that there are several legal issues that surround the use of these tags on your Web site. Danny Goodman, editor of SearchEngineWatch, has put together a page detailing the lawsuits brought on revolving around META tags. At the present time there have already been at least five such suits, mainly focused on sites that utilized someone else’s keywords within their META tags. The largest of these suits brought a settlement of $3 million dollars. Bottom line: use your own keywords, and definitely not words that someone else has a copyright on.

Next Page »