Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

May 30 2013

15:52

Fries: Free Framework for Developing Android Apps Using HTML, CSS and JavaScript


  
fries-homepage-w550

Fries by Jaune Sarmiento just reached version number 1.0. The project offers a framework for the development of web apps in the look and feel of native Android apps. If you are familiar with Android’s UI from version 4 on, you will definitely know your ways around, once you get a hold of Fries. In its current iteration, Fries is optimized to cooperate with PhoneGap, thus letting you build native Android experiences.

February 26 2012

10:00

25 Free and Premium Barebone WordPress Themes for Easy Customizing

If you design and develop themes for WordPress, chances are you probably already know the importance of theme frameworks or skeleton themes. To put it simply, these are minimal versions of themes, stripped of all additional functionality, giving you just the bare minimum level of code that you can work with and base your projects on. Needless to say, such frameworks and skeleton themes can save a lot of time and effort by giving developers a ready-made starting ground (consider this: you’re building a house, but you need not lay the foundation, as it’s already there. You simple shoot off with the main building).

Such themes are known by various names – bare-bones, stripped themes, blank themes, etc. Whatever it be, at the end of the day, all of them serve one purpose – help developers create awesome themes!

We shall now take a look at some of the major WordPress theme frameworks and skeleton themes. Before we proceed, it should be worth noting that certain themes mentioned below, such as TwentyTen Five, are not skeletons as such, but they make an awesome starting point for your project anyway!

*Pricing for paid/premium themes is mentioned adjacent to their respective names. Themes/frameworks with no pricing are free.

1. Elemental (Basic license $59.99)

Major Features:

  • Custom control panel that lets you edit typography, navigation and other sections
  • Four widgetized areas
  • 12 custom page templates for sitemaps, contact forms, etc.
  • Custom widgets for social networking sites
  • Custom admin bar
  • Localization and translation support
Elemental

Elemental

Demo | Download

2. Toolbox

Major Features:

  • Supports HTML5
  • Ultra minimal
  • Custom page templates
  • One of the most well-known blank themes
Toolbox

Toolbox

Demo | Download

3. Bones

Major Features:

  • Built around the HTML5 Boilerplate
  • Organized CSS Files
  • Custom page templates
  • Available in two formats for WP: Classic, Responsive
  • Also available in HTML version for projects
Bones

Bones

Demo | Download

4. HTML5 WP Shell

Major Features:

  • Custom page templates
  • Dynamic sidebars
  • 404 and 503 error pages
  • iPhone detection
HTML5 WP Shell

HTML5 WP Shell

Demo | Download

5. Genesis (Standard License: $59.95)

Major Features:

  • Support for multiple columns and sidebars
  • Both full- and flexible-width templates
  • Excellent SEO
  • Unlimited support from the developers
Genesis

Genesis

Demo | Download

6. WordPress Theme Framework (Pricing: $6)

Major Features:

  • Built-in social media integration
  • related posts
  • breadcrumbs
WordPress Theme Framework

WordPress Theme Framework

Demo | Download

7. Thematic

Major Features:

  • 13 widget-ready areas
  • Grid-based layout samples
  • Modular CSS with pre-packaged resets and basic typography
  • Support for most WP plugins
  • Wiki-editable guide for customization
Thematic

Thematic

Demo | Download

8. Roots

Major Features:

  • Clean URLs
  • Based on HTML5 boilerplate
  • Additional styling for Gravity Forms plugin
  • Multilingual (roughly 10 languages)
Roots

Roots

Demo | Download

9. Whiteboard

Major Features:

  • Totally free and open source
  • More dynamic classes and IDs than any other WP framework
  • CSS3 animations
  • Flexible div structure
  • Fallback mechanism for older versions of WP
Whiteboard

Whiteboard

Demo | Download

10. Starkers

Major Features:

  • No non-semantic markups
  • Totally blank, ideal for developing your theme based on it
Starkers

Starkers

Demo | Download

11. Standard Theme (Standard License: $49)

Major Features:

Standard Theme

Standard Theme

Demo | Download

12. HTML5 Reset

Major Features:

  • Semantic HTML5 Markup
  • Widget-ready sidebar
  • Built-in support for jQuery, Modernizr and Analytics
HTML5 Reset

HTML5 Reset

Demo | Download

13. The Buffet Framework

Major Features:

  • SEO options such as breadcrumbs, headings and canonical URLs
  • Action and Filter hooks
  • Compatible with microformats
  • Ready for translation
The Buffet Framework

The Buffet Framework

Demo | Download

14. Ashford (Professional License: $49; Free version also available)

Major Features:

  • Can create over 250 page variations
  • Fully customizable web fonts and color styles
  • Mobile friendly
Ashford

Ashford

Demo | Download

15. Catalyst (Basic License: $77)

Major Features:

  • 800+ design options
  • Unlimited layout options
  • SEO-friendly
Catalyst

Catalyst

Demo | Download

16. Simon WP Framework

Major Features:

  • Flexible and free
  • Widget-ready
Simon WP Framework

Simon WP Framework

Demo | Download

17. PageLines Platform Pro (Professional License: $197)

Major Features:

  • Drag and drop framework
  • Extensions Marketplace (version 2.0)
PageLines Platform Pro

PageLines Platform Pro

Demo | Download

18. ATOM Framework

Major Features:

  • Context-aware layout selection
  • Custom tabbed widgets
  • Short codes, Ad Management, Gallery slides
  • Easily extendable code base
ATOM Framework

ATOM Framework

Demo | Download

19. Thesis (Personal License: $87)

Major Features:

  • Easy to use options’ panel
  • Excellent Premium Support
  • Flexible and SEO-friendly
Thesis

Thesis

Download

20. The Constellation

Major Features:

  • Responsive design
  • Based on HTML5 Boilerplate
  • SEO-friendly
The Constellation

The Constellation

Demo | Download

21. TwentyTen Five

Major Features:

  • An HTML5 upgrade of the default TwentyTen theme
  • Responsive design
TwentyTen Five

TwentyTen Five

Demo | Download

22. Sandbox

Major Features:

  • Semantic classes
  • Dynamic functions and microformats
Sandbox

Sandbox

Demo | Download

23. Hybrid Core

Major Features:

  • Modular Framework with a solid PHP code base
  • Breadcrumbs and custom shortcodes
  • Loop pagination
  • Translation-friendly
  • Post templates
Hybrid Core

Hybrid Core

Demo | Download

24. Prototype

Major Features:

  • Custom Page templates and backgrounds
  • Breadcrumbs and threaded comments
  • Post layout and stylesheets
  • Translation-ready
Prototype

Prototype

Demo | Download

25. Modularity (Standard Club Membership $99 per annum)

Major Features:

  • Homepage apps for slideshow and video
  • Special layouts for magazine sites
  • Simple Color Picker Tool for customizable colors
  • Support for video on iPhone and iPad
  • Fully widgetized
  • Translation-ready
Modularity

Modularity

Demo | Download

With that, we come to the end of this round-up. Do share your thoughts in the comments!

Sponsored post
feedback2020-admin
04:05

January 18 2012

19:33

Digging into Dojo: Premium Video Series

If you prefer the written word, we have a fantastic session on working with Dojo Toolkit, created by Andrew Burgess. However, for the visual learners among us, I also asked him to prepare a series of screencasts for the series as well. I’m pleased to announce that, today, we’ve released these videos exclusively to our Tuts+ Premium members.

Become a Premium member to read this tutorial/screencast, as well as hundreds of other advanced tutorials and screencasts from the Tuts+ network.

Maybe you saw that tweet: “jQuery is a gateway drug. It leads to full-on JavaScript usage.” Part of that addiction, I contend, is learning other JavaScript frameworks. And that’s what this four-part screencast series on the incredible Dojo Toolkit is all about: taking you to the next level of your JavaScript addiction.


Tuts+ Premium

The recently re-launched Tuts+ Premium is a service that provides top-tier training in a variety of creative fields. Whether you prefer books, visual training, or in depth tutorials, we have you covered. While we unfortunately can’t afford to provide the service for free, it’s only $19 a month – less than you’d spend on dinner.

I hope you’ll consider checking it out! In addition to learning a huge variety of new skills, it’s also a fantastic way to say thank you to Nettuts+.


September 24 2011

06:39

20 JavaScript Frameworks Worth Checking Out

The number of web applications being created and used has grown rapidly since the new millenium. And importantly, so has the sheer complexity of them — specially on the front end. No more static pages, no sir!

You have a ton of sections each interacting with each other and the server and yes, it’s as complicated as it sounds and just as hard to pull off. Today, I’d like to talk about a few, choice JavaScript frameworks that aim to simplify front end application development.


Why We Need Frameworks Like These

If you think jQuery is the answer, you lose a cookie and get an F grade!

Creating responsive, fluid, and maintainable interfaces for web apps isn’t as easy as one would imagine — there is data to be sent back to the server and the results parsed, data stores to be updated, views to be re-rendered and so much else that needs to be done in the background. Desktop developers have it much easier with robust tools and well defined workflows. Us, poor web devs? We’ve been twiddling DOM elements, creating models by hand and pulling our hair out trying to keep everything synched.

The monstrous rise in the number of web apps being built recently has really made it apparent that we need better tools and frameworks and the devs have responded with a staggering amount of solutions. Today, we’re going to go over just a few of these. A couple of these are quite old but I’m certain you can learn a lot from perusing their code base.

Sure, a few of these may be a little old but their code bases have lots of lessons to teach.


Sproutcore

Nettuts+ -- JavaScript Frameworks

Sproutcore powers a lot of high profile apps including MobileMe amongst others. Sproutcore has a steeper learning curve compared to the other options but makes up for it with developer productivity once he/she has learned the ropes.

This framework boasts a UI framework, the market standard MVC architecture and well written documentation.

Related links:


Cappuccino

Nettuts+ -- JavaScript Frameworks

Cappuccino was created by the 280North team, now owned by Motorola. This framework gained significant coverage with the release of the 280Slides — built completely with Cappuccino.

This framework varies dramatically from the others in that a developers doesn’t need to understand or work with any of the front end trifecta — HTML, CSS or the DOM. All you need to master is the framework!

Related links:


JavaScriptMVC

Nettuts+ -- JavaScript Frameworks

Built on jQuery, JavaScriptMVC is a veteran in the front end frameworks battlefield, dating back to 2008. Featuring a familiar, and obvious, MVC architecture, this framework is quite full featured with support for code generators, testing and dependency management.

Related links:


Asana Luna

Nettuts+ -- JavaScript Frameworks

Luna is one of those hush-hush private frameworks that people have been talking about. And for good reason, I must admit.

The framework features a lot of niceties including an evolved MVC architecture, pubsub, caching, routing and authentication.

Related links:


Backbone.js

Nettuts+ -- JavaScript Frameworks

Backbone supplies structure to JavaScript-heavy applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing application over a RESTful JSON interface.

Related links:


qooxdoo

Nettuts+ -- JavaScript Frameworks

qooxdoo is a universal JavaScript framework that enables you to create applications for a wide range of platforms. With its object-oriented programming model you build rich, interactive applications (RIAs), native-like apps for mobile devices, light-weight traditional web applications or even applications to run outside the browser.

Related links:


Spine

Nettuts+ -- JavaScript Frameworks

Spine is a lightweight framework for building JavaScript web applications. Spine gives you a MVC structure and then gets out of your way, allowing you to concentrate on the fun stuff, building awesome web applications.

Related links:


ActiveJS

Nettuts+ -- JavaScript Frameworks

ActiveJS is a JavaScript application framework that provides local and REST based data modeling and pure DOM view construction with back button and history support along with framework agnosticm and lack of external dependencies.

Related links:


Eyeballs

Nettuts+ -- JavaScript Frameworks

eyeballs.js is a slim javascript library designed to sit on top of a javascript framework, such as jQuery or Prototype. eyeballs.js can sit on top of an already implemented web app with a well thought out object model. It can also be used to build standalone javascript apps, backed by HTML5 local storage or something like CouchDB.

Related links:


Sammy

Nettuts+ -- JavaScript Frameworks

Sammy.js is a tiny JavaScript framework developed to ease the pain and provide a basic structure for developing JavaScript applications.

Sammy tries to achieve this by providing a small ‘core’ framework and an ever-growing list of plugins for specific functionality.

Related links:


Choco

Nettuts+ -- JavaScript Frameworks

Choco brings the MVC to the client side! A Choco app consists of only one HTML page, all the interactions are managed by Javascript. Your UI only uses HTML and CSS!

Related links:


Agility

Nettuts+ -- JavaScript Frameworks

Agility.js is an MVC library for Javascript that lets you write maintainable and reusable browser code without the verbose or infrastructural overhead found in other MVC libraries. The goal is to enable developers to write web apps at least as quickly as with jQuery, while simplifying long-term maintainability through MVC objects.

Related links:


Angular

Nettuts+ -- JavaScript Frameworks

Angular supports the entire development process, provides structure for your web apps, and works with the best JS libraries. With angular, the view and data model are always in sync — there is no need for manual DOM manipulation.

Angular is small, weighing in at 60kb, is compatible with all modern browsers and works great with jQuery.

Related links:


ExtJS

Nettuts+ -- JavaScript Frameworks

Ext JS 4 brings a whole new way to build client applications, by introducing the popular model-view-controller pattern to Ext JS. By allowing the separation of data management, logic and interface elements, Ext JS 4 makes it easier for even large development teams to work independently without worrying about stepping on each other’s toes. Ext JS 4 ships with a helpful MVC guide to get started.

Related links:


Knockout

Nettuts+ -- JavaScript Frameworks

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

Related links:


Jamal

Nettuts+ -- JavaScript Frameworks

Jamal is a set of conventions and small javascript libraries to archieve a complete separation of html, css and javascript in your web application. Jamal is built on jQuery and inspired by MVC frameworks like Ruby on Rails, CakePHP and its derivatives.

Related links:


PureMVC

Nettuts+ -- JavaScript Frameworks

PureMVC is a lightweight framework for creating applications based upon the classic Model, View and Controller concept.

Based upon proven design patterns, this free, open source framework which was originally implemented in the ActionScript 3 language for use with Adobe Flex, Flash and AIR, is now being ported to all major development platforms.

Related links:


TrimJunction

Nettuts+ -- JavaScript Frameworks

The open source Junction framework is a conventions-over-configuration, synchronizing web MVC framework for JavaScript. TrimPath Junction is a clone or port of the terrific Ruby on Rails web MVC framework into JavaScript.

Related links:


CorMVC

Nettuts+ -- JavaScript Frameworks

CorMVC is a jQuery-powered Model-View-Controller (MVC) framework that can aide in the development of single-page, web-based applications. CorMVC stands for client-only-required model-view-controller and is designed to be lowest possible entry point to learning about single-page application architecture.

Related links:


batman

Nettuts+ -- JavaScript Frameworks

batman.js is a full-stack microframework extracted from real use and designed to maximize developer and designer happiness. It favors convention over configuration, template-less views, and high performance by simply not doing very much. It all adds up to blazingly fast web apps with a great development process; it’s batman.js.

Related links:


That’s a Wrap!

And we’re done here. The number of options here might border on overdoing things at first glance but each of these are a little different in how they tackle this problem and given a problem, different solutions and choices are always a welcome addition.

As I mentioned earlier, if you think a framework should be here but isn’t, just drop us a line below and we’ll update this roundup accordingly. Thank you so much for reading!


June 27 2011

10:00

An Introduction to Object Oriented CSS

With richer interactions and media heavy pages mushrooming on the web, creating web pages, which load faster and respond well has become a challenge. Separating the content, presentation and behavior of a page using HTML, CSS and JS, is not the only thing that front-end engineers have to concentrate on nowadays. The limelight is now on the performance of the pages, cleanliness and leanness of the code within, scalability and reusability of CSS, and the semantic correctness of the markup.

There are a handful of frameworks, techniques and approaches that are built towards this goal of maintainability, scalability and reusability of CSS. Each of them is having its own pros and cons. But, this is not a stage to elaborate on all of them.

This article is an introduction to implementing the concept of ‘Object Oriented Programming’ in building CSS for high scale websites and applications, with an eye on maintainability and reusability.

What is OO CSS?

The concept of ‘Object Oriented Programming’, is widespread among developers, and forms the basic for any modern programming language. Features like data abstraction, modularity and inheritance make it a favorite in coding large-scale applications.

Object Oriented CSS, as the name suggests, is implementing the concepts of OOP in structuring and building CSS rules, which are easy to reuse, thereby reducing the loading time and increasing the performance of web pages incredibly! The key point here is, to identify, build and style modular reusable ‘objects’ in a page, and to reuse it in multiple instances by extending them with additional features wherever needed. Here an ‘object’ refers to the basic HTML markup and its CSS rules. Apparently, here, the key challenge is going to be, identifying the ‘object’ and building rules for it.

This is neither a framework nor a technology, but an approach adopted in building the rules, so as to make the code more reusable, maintainable and scalable. You may already have been making use of this concept in coding your style-sheet for years, but may not be aware of this terminology :).

A UI engineer at Yahoo (‘Nicole Sullivan’ ) coined the term. She had made a number of presentations on the topic on various big stages (http://developer.yahoo.net/blogs/theater/archives/2009/03/website_and_webapp_performance.html) and is also included in a feature on Women in Technology.

Nicole, who has been hired by Facebook recently, for optimizing the CSS and web page performance, has been leading the way in implementing this approach in the pages for the social networking giant, and the results are to be seen. A faster loading FB, with significantly less response time! This is exactly what this approach of building CSS promises to give back. But again, like all other frameworks, this too has pitfalls and advantages which we shall discuss in detail.

Following are some key aspects in object-oriented approach to CSS building:

  1. Create a component library
  2. Separate container and content / Avoid Location dependent styles
  3. Separate Structure and skin
  4. Extend base objects using class names
  5. Stick to semantic class names

Create a component library

This is the first thing to do, while building a OO CSS framework for your application, and this is the most time consuming process too. You will have to carefully study the screens of the app, and come up with the recurring reusable UI patterns, and will have to create a library consisting of HTML markup and respective CSS rules of all such components first. This may take some initial time, as you may need to filter out the components and find out the basic structure of a component, and its variations along different screens.

E.g. For a blog, ‘metadata (Refer to the marked area in the figure below)’ will be present in multiple instances of a page. After closer scrutiny, you will come to know that, all the metadata can have the same HTML markup, and the variations can be addressed using CSS (the font size, color, margin and padding are different in each of the occurrences of metadata component). Select a markup, as a base structure, in which you can accommodate majority of the elements that possibly can come in the particular component.

In our example our basic structure of the ‘metadata’ component will be:

Base Markup


<p class=”metadata”><a>Author name</a>commented on<a>21-02-2010</a>@</p>

Base rule


.metadata{font-size:1.2em; text-align:left; margin:10px 0;}

Thus, ‘metadata’ can be now independently used within any other element in the markup, and will have a consistent look and feel, irrespective of where it is used. But as we can see in the figure above, there are multiple variations of the component. This we will tackle using CSS, and will be discussing in the following points.

This way, figure out all the reusable components, and create rules and markup, and group them separately in the CSS file. (It’s even fine to create a separate CSS for the component library, and then merge it with others later during deployment.)

Separate Content from Container / Avoid location dependent styles

This is one of the primary requirements of following an OO approach to building CSS files. The core idea here is to consciously differentiate the rules of containers and the content that comes within them, so that content can be plugged into any containers irrespective of their parents.

Often while building large-scale CSS rules there will be instances where a single component will be appearing differently in various instances, when put in different containers. One of the solutions adopted by front-end engineers, for addressing this problem was to assign location dependent selectors to that particular component.

E.g. With reference to the example used in the previous point, where there are multiple variations of the same component – ‘metadata’, each instance can be given location dependent rules by combining the base class ‘metadata’ with the relevant classes/IDs for the containers. i.e.,

‘metadata’ in a blog post can be styled as: .post .metadata{overriding rules}
‘metadata’ in a comment can be styled as: .comment .metadata{overriding rules}
‘metadata’ in a comment can be styled as: .comment .metadata{overriding rules}

The OOCSS approach advocates avoiding this type of usage. Instead extend the base class by adding more classes, thereby extending the attributes of the base component to match the variation. We shall discuss the concept of extending the base class in the following points.

Separate structure and skin

In the first point ‘Creating component library’, we discussed the importance of identifying reusable components, and building base classes and base structures for them. While creating those base rules, an important thing to keep in mind is to separate the structure and skin. In other words, while defining a base class in the component library, we should not create skin-level rules, like width, height, background images, border styles, etc, that can make the component more specific to a certain container.

E.g. For our base class, ‘metadata’ with the following rule

.metadata{font-size:1.2em; margin:10px 0;},

Adding more skin-level rules as below,


.metadata{font-size:1.2em; margin:10px 0; <strong>width:500px; background-color:#efefef; color:#fff;</strong>},

can make it more of a specific component than a generic one, thereby making it difficult to reuse it in many other containers, which would need it to be rendered in a different ‘skin’. Also another danger of not separating structure and skin will be the ‘Specificity war’.

Extend base objects using class names

As discussed in the second point ‘Separate content from container’, avoiding the usage of contextual selectors will make the content independent from their parent containers and hence will be truly usable across the application. So how do we instantiate the variations of the same object in different containers? What is the solution? Well here comes the concept of extending the base ‘object’ (again another term coined by Nicole Sullivan), by adding more class names to it depending on the context, rather than tightly coupling the object with the class names of the containers in which it is to be placed.

E.g. In the first figure of the ‘metadata’ object, where the same object needs to be rendered differently in various containers,

The HTML markup of each of them will look like:

<p class=”metadata commentmetadata”><a>Authorname</a>commented on<a>21-02-2010</a>@</p>
<p class=”metadata postmetadata”><a>Authorname</a>commented on<a>21-02-2010</a>@</p>
<p class=”metadata authorlistmetadata”><a>Authorname</a>commented on<a>21-02-2010</a>@</p>

The CSS rules will be:


.metadata{font-size:1.2em; margin:10px 0;}
.commentmetadata{font-size:1em; margin:0 0 10px 0; color:#063070; }
.postmetadata{ color:#063070; }
.authormetadata{ color:#fff; }

This is a very simple demonstration, to comprehend the concept of implementing OO programming. As the size of the app becomes larger, the UI patterns will become more complex, and there lies the actual challenge and advantage of using such an approach.

Stick to semantic class names

A challenge in building CSS for high-scale web applications is to logically come up with meaningful class / ID names matching with the context and moreover making sure, they are reusable and still make sense. With the concept of ‘extending’ base objects, it’s easy to fall into the practice of creating ‘presentational class names’. Some easy examples are ‘leftCol’, ‘redText’, ‘midCol’, ‘bigText’, ‘bolderText’ etc. Such class names are not reusable and are a hindrance to scalability.

Always stick to logical and semantic class names relating to the logical meaning of the component, rather than its presentational meaning. It means, instead of giving the text block with a yellow background color, the class name ‘yellowText’, ‘notification’ would be a more sensible name, as it is a notification element that pops out to notify some activities within the system.

Pros and Cons?

Following such an approach of building CSS has its own pitfalls and advantages

Here are a few cases, where adopting such a framework ‘may’ backfire:

  1. OOCSS is suited to really large websites / application which are filled with reusable components. It may not give desired results in smaller websites and applications. So decide sensibly depending on the size of the work in hand
  2. If not smartly used, creating the component library can turn out to be a mess, and become a maintenance nightmare for other coders
  3. Documentation is a must. Each block of code should be clearly commented out with the right points for other coders to absorb the concept, which otherwise can become too tedious in case of a knowledge transition

Some obvious advantages of adopting this approach are:

  1. Less lines of CSS code
  2. Cleaner HTML markup, with logically sensible class names and hierarchy
  3. Semantic markup, means more SEO friendly pages
  4. Far better page optimization, with much faster loading times, since most of the components are reused
  5. Scalable markup and CSS code, where more components can be added into the library without disturbing other components, as the base objects are independent of any other containers
  6. Easily theme-able layouts, since changes to the base object can completely change almost the whole presentation layer instantly

Courtesy & Resources

http://www.webdirections.org/blog/object-oriented-css-the-video/

http://www.stubbornella.org/content/2009/02/28/object-oriented-css-grids-on-github/

http://www.iconfinder.com for all the icon resources

May 28 2011

10:00

Pros And Cons Of Using Frameworks

Sometimes you should ask yourself, why you need to do the same thing everyday when there’s a new bridge to shorten the path. Think of a framework as a bridge that will help you code faster and easier. Did you notice I didn’t include the word “better” in the last sentence? Faster and easier doesn’t always mean better, but we will get to that later.

First things first, so what is a framework really? It actually depends on the context it is used. It can be defined as an abstraction tool that makes it easier to develop applications and reuse code.

“The framework aims to alleviate the overhead associated with common activities performed in Web development… and they often promote code reuse.”

Like everything else, when it comes to its use, a framework has advantages and downsides. Below is a list of some important facts you should consider, before you decide to start learning or using one.

Pros

Pros of using a framework

Efficiency

Tasks that usually would take you hours and hundreds of lines of code to write, can now be done in minutes with pre-built functions. Development becomes a lot easier, so if it’s easier it’s faster, and consequently efficient.

Security

A widely used framework has big security implementations. The big advantage is the community behind it, where users become long-term testers. If you find a vulnerability or a security hole, you can go to the framework’s website and let the team know so they can fix it.

Cost

Most popular frameworks are free, and since it also helps the developer to code faster, the cost for the final client will be smaller.

Support

As any other distributed tool, a framework usually comes with documentation, a support team, or big community forums where you can obtain quick answers.

Cons

Cons

You learn the framework, not the language

I believe this to be the major problem. If you’re using a framework and you know very little about the language behind it, you will learn the framework and not the language itself. The way you code jQuery is different from the way you code javascript. Simple put, if you know jQuery, it doesn’t mean you know javascript.

Limitation

The framework’s core behaviour can’t be modified, meaning that when you use a framework, you are forced to respect its limits and work the way it is required. Make sure you choose a framework that suits your needs.

Code is public

Since the framework is available to everyone, it is also available to people with bad intentions. It can be studied in order to know how things work and to find flaws that can be used against you.

JavaScript Frameworks

jQuery

http://jquery.com/

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

jQuery


Prototype

http://www.prototypejs.org/

Prototype is a JavaScript Framework that aims to ease development of dynamic web applications. Featuring a unique, easy-to-use toolkit for class-driven development and the nicest Ajax library around, Prototype is quickly becoming the codebase of choice for web application developers everywhere.

Prototype


Mootools

http://mootools.net/

MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API.

Mootools


PHP Frameworks

CodeIgniter

http://codeigniter.com/

CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications.

Codeigniter


CakePHP

http://cakephp.org/

CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications.

CakePHP


Symfony

http://www.symfony-project.org/

Symfony is a full-stack framework, a library of cohesive classes written in PHP.

Symfony


Mobile Frameworks

jQuery Mobile

http://jquerymobile.com/

Query mobile framework takes the “write less, do more” mantra to the next level: Instead of writing unique apps for each mobile device or OS.

jQuery Mobile


iWebKit

http://snippetspace.com/projects/iwebkit/

iWebKit is a file package designed to help you create your own iPhone, iPod Touch and iPad compatible website or webapp.

iWebKit


DHTMLX Touch

http://www.dhtmlx.com/touch

DHTMLX Touch is an HTML5-based JavaScript library for building mobile web applications. It’s not just a set of UI widgets, but a complete framework that allows you to create eye-catching, cross-platform web applications for mobile and touchscreen devices.

DHTMLX


Ruby Frameworks

Ruby on Rails

http://rubyonrails.org/

Ruby on Rails is an open-source web framework that’s optimized for programmer happiness and sustainable productivity.

Ruby on Rails


Padrino

http://www.padrinorb.com/

Padrino is a ruby framework built upon the excellent Sinatra Microframework. Sinatra is a DSL for quickly creating simple web applications in Ruby.

Padrino


Bowline

http://bowlineapp.com/

Bowline is a framework for making cross platform desktop applications in Ruby, HTML and JavaScript.

Bowline


CSS Frameworks

Blueprint

http://www.blueprintcss.org/

Blueprint is a CSS framework, which aims to cut down on your development time.

Blueprint


960 Grid System

http://960.gs/

The 960 Grid System is an effort to streamline web development workflow by providing commonly used dimensions, based on a width of 960 pixels.

960 Grid System


YUI2

http://developer.yahoo.com/yui/grids/

The foundational YUI Grids CSS offers four preset page widths, six preset templates, and the ability to stack and nest subdivided regions of two, three, or four columns.

Yui2


Considerations

Now you understand why I didn’t include the word “better” on my first sentence. A framework can bring you several advantages and may suit your needs, but it also brings downsides to your projects. There are hundreds of frameworks out there, so be sure to choose carefully, if you plan to use one in the future.

May 22 2011

10:00

20+ Useful CSS3 and HTML5 Frameworks, Tools and Templates

I hope you have heard a little about CSS3 and HTML5. And I’m sure you’ve used at least one of the cool features they offer. But now it is time to use them at their full (or almost full) power.

You may be asking yourself “It is time to change? Should I forget everything I know and dive into this new world?”. Well dear padawan, you don’t need to do so. We have a lot of tools that make our transition to new and better technologies safer (ultimately we can’t just crash our customer’s website, we have bills to pay :D).

Frameworks are helpful with this. They’ve already been tried, tested and proven. Of course, you can always make them better, but they are a really good starting point.

This time we will talk a little about frameworks and other tools, like generators and templates.

So, let’s rock.

HTML5 Boilerplate – Templating that fits all needs

This is the most useful for me. I usually have jobs that need easy setup, but a lot of optimizations tools (minifiers and more) and, at the same time, I’m quite familiar with CSS, so too much preset CSS is a waste of time to me (since I spend a few hours coding CSS, but much more to understand and re-utilize framework’s code).

Cool features:

  • Constantly improving – Last update says that they reduced the overall size of the published boilerplate by 50%
  • Build script – .js and .css minify, image optimization, html optimization, server configurations for caching…
  • Custom install setup – So you can choose what you want in “your” boilerplate
  • Cross-Browser compatible
  • HTML5 Ready
  • Print stylesheet ready to use

52framework – Supports almost anything

I am amazed by all the things you can do with this framework. It has a lot of resources that I thought would never work on IE. This is a good option when you want a somewhat styled template and  are planning to use almost all power of HTML5.

What do I like:

  • Almost anything you want with HTML – Local Storage, video player, canvas, forms…
  • A lot of CSS3 proprieties – As you can see in CSS demo, it has a good CSS3 support
  • Video Tutorials – Yeah, it makes even easier to understand 52′s workflow

G5 Framework – Good tools collection

Actually Greg Babula says that it meant to be just a personal project. But it is much powerful than he thinks.

As it was made from personal experience, it has a lot of tools that we already know how to use (Modernizr, CSS Reset, jQuery, Orbit Image Slider…), thus we don’t waste too much time learning.

Perkins – Lighweight and LESS

I must admit that I should use LESS much more than I do. If you think this way, Perkins may be a good option for you. It comes with a set of LESS stylesheets and mixins for common tasks such as creating navigation, rounded corners, gradients and much more.

Sprites.js – Animation framework (HTML5 support, of course)

Yeah, sometimes our customer wants some animations on their site. Why should you use flash when (almost every time) you can use HTML5?

Sprite.js provides a simple integration for canvas and HTML animations so you can do easily some animations, with maximum performance.

Lime.js – Gaming framework

Just take a look at the demo games, and tell me if it isn’t amazing.

Some features (HTML5) that you can use on it:

  • Optional install – For mobile users it is really good, just bookmark your game and you’re done
  • KeyFrame animations
  • Full support of sprite sheets
  • Stroke support – So you can draw a stroke around shapes
  • Good documentation – Just take a look at all classes you can use with it, pretty cool :D

HTML5 multimedia framework for WordPress

If you are a WordPress person, you will find it useful. With this plugin, you just have to add a shortcode and you have a HTML5 media player in your site.

The framework currently supports:

  • mp4 (h.264,aac)
  • ogg (theora,vorbis)
  • mp3 (audio only)
  • webm (vp8,vorbis).
  • wmv (via MediaElement.js)
  • flv (via MediaElement.js)
  • wma (via MediaElement.js)

Modernizr – HTML5 & CSS3 with fallbacks

Modernizr helps us to implement HTML5 and CSS3 for browsers that don’t natively support it. Actually many of the tools mentioned above use it.

Want to know more about its amazing features? Just read The All-In-One Entirely-Not-Alphabetical No-Bullshit Guide to HTML5 Fallbacks.

It is really simple to use, when modernizr detects your browser’s features, it adds classes to you HTML, so you can easily switch to a valid fallback. Try to run the demo and see its results for a better comprehension.

Select[ivizr] – CSS3 Selectors for IE

IE (6-8 mainly) is surely the greatest barrier to CSS3 spread. CSS3 selectors are almost forgotten for some developers, that just know they exist because can use them with jQuery.

You just need one of the 7 supported JavaScript libraries and you are ready to install it (via conditional comments, so just IE will see it). And then you’re done, just write you pretty CSS3 selectors as you aways wanted.

CSS3 button framework

With this framework you have easily a lot of good buttons options. It is specially useful for back-end developers, that aways need some pretty buttons, but don’t have time (or budget) to do so.

They are all CSS3 ready, and can be easily customized.

Templates – General HTML5 and CSS3 samples

Coming Soon Template

Design Company

Real State

Free HTML5 & CSS3 theme

Create An Elegant Website With HTML 5 And CSS3

Starter Pack

Much more inspiration at HTML5 Gallery

Some useful tools

CSS3 Button Maker

CSS Transforms code generator

CSS3 Gradient generator

CSS3 Drop Shadow Generator

CSS Generator for radius, shadows, rgba, @font-face, columns and more

The best @font-face generator I’ve ever seen

HTML5 Visual Cheat Sheet

Ready to start experimenting with HTML5?

You may notice that I didn’t even mention any mobile frameworks. It is because they are so cool that they deserve a dedicated post.

I certainly have missed some other good resources. Why don’t you comment and share what you know?

November 10 2010

01:02

How to Create a Config Variables Loader in CodeIgniter: New Premium Tutorial


If you’ve been using CodeIgniter or another MVC framework for any length of time, you’ve probably started to realize the advantage of abstracting data and logic from presentation. But efficiency is not without its drawbacks, and, in the case of CodeIgniter, one of these drawbacks is the need to constantly bounce variables out of your controllers so that they are available within your views.

In this tutorial, I’ll show you a really cool way to eliminate this hassle. Become a Premium member to gain access to this tutorial, as well as hundreds of other tutorial, screencasts, and freebies from the Tuts+ network.

We’re going to build a config loader that automatically loads all of your important site variables and makes them available globally. Even more cool, your site variables will be stored in a separate config file that you can append or edit whenever you like. Not only will this save you a lot of time (and errors!), but it will help you develop a killer workflow that you can build on for all your projects. Lets get started!


Join Net Premium

Screencasts and Bonus Tutorials

For those unfamiliar, the family of Tuts+ sites runs a premium membership service. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, Vectortuts+, and CgTuts+. For the price of a pizza, you’ll learn from some of the best minds in the business. Become a Premium member to read this tutorial, as well as hundreds of other advanced tutorials and screencasts.

October 22 2010

10:00

A Complete Beginner’s Guide to Zend Framework: Part 2

A Complete Beginner’s Guide to Zend Framework: Part 2After reading the first part of our series, you’ve learned how to create a simple website based on Zend Framework. But it’s necessary to keep the information for full web-application. In this part we will learn how to work with databases using ZF.

Zend_Db

Zend_Db_Adapter gives us an opportunity to work with different database management systems (DBMS).

Using PDO drivers:

  • BM DB2 and Informix Dynamic Server (IDS), using pdo_ibm extension
  • MySQL, using the pdo_mysql PHP extension
  • Microsoft SQL Server, using pdo_mssql
  • Oracle, using pdo_oci
  • PostgreSQL, using pdo_pgsql
  • SQLite, using the pdo_sqlite PHP extension

Using PHP extensions:

  • MySQL, using the mysqli extension
  • Oracle, using the oci8 PHP extension
  • IBM DB2, using ibm_db2
  • Firebird / Interbase, using php_interbase

We’ll use the PDO driver to work with MySQL in this article.

Let’s Get Started

We need the way to store configuration file to the database connection. For it we’ll create a application.ini file in our ./application/configs directory. Add to the file following lines:

	db.adapter          = "pdo_mysql"
	db.params.host      = "localhost"
	db.params.username  = "root"
	db.params.password  = ""
	db.params.dbname    = "your_db_name_here"

I think the content will not cause any difficulties for you. We will use Zend_Confg_Ini to parse the config of this file. You have to initialize connection to the database before dispatching process. Add the following code to your index.php file.

	// Load up our config file
	$config = new Zend_Config_Ini('./application/configs/application.ini', 'db');

	$db = Zend_Db::factory($config->db->adapter,
				   $config-db->config->toArray());

	// Return data as object
	$db->setFetchMode(Zend_Db::FETCH_OBJ);

	// The default adapter for table classes
	Zend_Db_Table::setDefaultAdapter($db);

	// Write our adapter to registry
	Zend_Registry::set('db', $db);

If you do not want to receive the result as an object, there are descriptions of other styles to obtain the result for you:

  • Zend_Db:: FETCH_ASSOC: returns the data in an associative array.
    The keys of the array are the column names. It’s the mode of extraction is used by default in Zend_Db_Adapter classes.
  • Zend_Db:: FETCH_NUM: returns the data in an array. The array indexed by integers in accordance with the position of the field in the select query list.
  • Zend_Db:: FETCH_BOTH: returns the data in an array. The keys of the array are lines and integer values. The number of elements will produce twice more in the array than if FETCH_ASSOC or FETCH_NUM is used.
  • Zend_Db:: FETCH_COLUMN: returns the data in an array of values. The value is the value returned from one column of the result set in each array. By default, it’s the first column, indexed by zero.
  • Zend_Db:: FETCH_OBJ: returns the data in an array of objects. By default, the built-in PHP class stdClass is used. Columns of the result of sample are available as public properties of this object.

You are probably interested why have we recorded the adapter to the registry? We did so to be able to get access to our created adapter in any controller or model. To extract our adapter from the registry back we can use Zend_Registry::get(); method

	Zend_Registry::get('db');

Well, let’s try to execute some requests!

	$sql = 'SELECT * FROM users';
	$result = $db->fetchAll($sql);

The $result variable will contain an array of objects. To extract a single column from the sample results you should do

	$sql = 'SELECT name, id FROM users';
	$result = $db->fetchCol($sql);

Now $result contains only the name. In order to extract a single row from the result of sampling execute the following code

	$sql = 'SELECT * FROM users WHERE id = 2';
	$result = $db->fetchRow($sql);

And now $result is the single object ($result->name). Extracting a single value

	$sql = 'SELECT COUNT(*) FROM users';
	$result = $db->fetchOne($sql);

$result contains the number of users. That’s all with SELECT queries. But we still have to add and modify our data in the database. Lets’s look at it.

Adding Records

There is a special method for inserting data to the database: Zend_Db’s insert method.

	$data = array('name'  => 'Nick',
				  'login' => 'nick',
                  'email' => 'myemail@gmail.com');

	$db->insert('user', $data);
	$lastId = $db->lastInsertId();

We need to pass two parameters to insert method: table name, and an associative array with the data. lastInsertId method will return the value of auto-increment primary field in the table.

Updating Records

To able to update our db data we should call the update method and pass it three parameters. The first parameter is the name of the table, the second – an associative array with the data, the third parameter – a condition (optional); if you omit the third parameter, all records will be updated. The array of conditions can be passed as a WHERE condition.

	$data = array('name'  => 'Nick',
		          'login' => 'nick',
                  'email' => 'myemail@gmail.com');

	$db->update('user', $data, 'id = 1');

Deleting Records

Now you should know what each parameter is used for. The first argument is the name of the table, the second is the condition. Simply, right? Also there may be several conditions which is passed as an array. If you omit the second argument, all records of the table will be deleted.

	$db->delete('user', 'id = 1');

Example Bits of Code

Example 1:

	// Extract Zend_Db_Select
	$select = $db->select();	

	// 1st - table name, 2nd - array of selecting columns
	$select->from('news', array('YEAR(date) AS yearNews',
		'MONTH(date) AS monthNews',
		'DAy(date) AS dayNews'));

Example 2:

	// Extract Zend_Db_Select
	$select = $db->select();	

	// Descending sorting
	$select->from('news')->order('date DESC');
	$result = $db->fetchAll($select);

Example 3:

	// Extract Zend_Db_Select
	$select = $db->select();	

	// Descending sorting by date and ascending by title field
	$select->from('news')
		->order(array('date DESC', 'title'));

	$result = $db->fetchAll($select);

Example 4:

	// Extract Zend_Db_Select
	$select = $db->select();	

	// Descending sorting by date and ascending by title field
	$select->from(array('n' => 'news'), // table name and its alias
				array('newsTitle' => 'title', // The second parameter
						'newsDescription' => 'description', // column alias => column name
					'date' => 'date'))
			->join(array('a' => 'author'), // The first param for join method | alias => table name
					array('n.author = a.id'), // The 2nd param - array of condition for join operator
					array('name' => 'authorName')) // Associative array of columns
			->order('date DESC'); // Sorting descending by date column

	$result = $db->fetchAll($select);

Zend_Db_Select

Zend_Db_Select – is the assistant of making SELECT queries. Using this class methods we can build our complicated queries expressions part-by-part.

Queries Building

For example, we have to choose the record of news from a table with this query

	SELECT * FROM news WHERE id = 12;

Using Zend_Db_Select it would look like so

	// Extract Zend_Db_Select
	$select = $db->select();

	$select->from('news')->where('id = 12');
	$result = $db->fetchAll($select);

Now, let’s choose all the news records, but breaking the date’s field into three columns – year, month, day

SELECT *, YEAR(date) AS yearNews,
	MONTH(date) AS monthNews,
	DAY(date) AS dayNews
FROM news;

SQL has several types of joining operation. Below are the list of methods for supporting different joining types in Zend_Db_Select.

  • INNER JOIN, methods join (table, join, [columns]) and joinInner (table, join, [columns]).
  • LEFT JOIN, the method joinLeft (table, condition, [columns]).
  • RIGHT JOIN, the method joinRight (table, condition, [columns]).
  • FULL JOIN, the method joinFull (table, condition, [columns]).
  • CROSS JOIN, the method joinCross (table, [columns]).
  • NATURAL JOIN, the method joinNatural (table, [columns]).

There are also some special methods of Zend_Db_Select class.

  • orWhere() – the same as where(), but with logical OR.
  • group() – one column’s name can be sent to this method by one line or the lines’ array of columns’ names./li>
  • limit() – passes the desired number of rows to choose by the first parameter, by the second – number of the optional rows which can be omitted.

The Result

Another one Zend Framework lesson is completed. Digest the received knowledge, and I hope we will try to continue our experiment in the next part. Bye!

P.S. I look forward to receiving your feedback and questions in the comments below.

October 19 2010

10:00

A Complete Beginner’s Guide to Zend Framework: First Steps

Getting into Zend Framework: First StepsYou’ve been still tormenting and write-ins of the same type in the n-times for the site? You do what has been done for you and try to divide the project design from the code? Looking for realization of the necessary functions in questionable forums? If you answered “yes” one of these questions, so this article is definitely for you. There I will tell you about the powerful free framework (Content Managment Framework), if you learn it you will not only save time for the design, but also rtake the quality of your work to a much higher level. So, let’s sit comfortably and read my first article of the series “Learning to work with Zend Framework”.

Why to use Zend Framework?

The major aim for any CMF – reduce time for a project’s working up. Using this product, you can achieve following:

  1. Permanent structure of your projects. The problem of majority projects, making from nothing, – absence of a permanent structure. First, you put necessary function in one module, in the next project you realized you’d made a mistake and decided to change everything. As a result, the more you create a website / web-applications, the more you improve your knowledge, well then you make changes in the structure of new projects. But now try to imagine that you will have to go back to support/revision of your oldest project. I’m sure you’ll just get entangled or waste much of time for the code’s investigation. When you create a web-based application frameworks, this problem disappears, because you’re always guided by rules. This approach can guarantee that, if the oldest project’s revision is necessary, you will always know its structure and can finish it off easily.
  2. Increase the speed of development. There is a set of classes in ZF that allow to realize a lot of typical actions. You’ll not need to create one more bicycle cause you have the whole Kamaz of ready-made bicycles.:)
  3. Increase the level of safety. Everybody makes mistakes and no one is safety. It is difficult to argue, but with the help of ZF you can significantly reduce the error rate in the project. Because it’s really to make a lot of typical actions with the help of built-in classes, it means you have to write less code. And less code, less errors.

Is It Difficult?

Someone says that ZF is too complicated for understanding, heavy, requires a lot of server resources. It’s not like this in reality. If you can to learn php, so moreover you can deal with ZF, and as for heaviness, a good diet will eliminate this shortcoming with no problems.

Positive and Negative Of ZF

There are no ideal solutions and ZF is not the exception. It has its both positive and negative sides, which we’ll discuss in this part. Let’s start with the negative:

  1. Heavy, version 1.8.a for exaple is 17 MB (well, not be afraid of), although this is not so much. If you’re scared this size, see the size of many commercial CMS. Almost of them rolled over for 10 MBs and it is not surprising, cause they have a lot of functions. It is the similar story with ZF. It provides a lot of opportunities, but it’s not the fact that you can use them all.
  2. Requires a lot of time to study. Actually, this all is individually here. Some may mark time a year, while it will be enough for others just a few days and they are ready to write their first applications.
  3. Resource-intensive. To be honest, I have not seen more than one hosting provider that would kick the bucket from ZF.

That’s all the negative sides. Now the positive:

  1. ZF is a set of classes, most of which are not tied to each other, so that it can be used as the spare parts in other projects and completely. There is all you need in today’s Web projects.
  2. The presence of a component to work with third-party services.
  3. Object-oriented approach.
  4. MVC pattern based.
  5. Well documented.

So, it’s enough, no more theory and let’s go straight to practice. We estimate the possibility of the giant, so to speak:) Inorder to work with ZF, we need ZendFramework (you can download the latest version from here, HTTP server with the mod_rewrite support, PHP at least version 5.2, and MySQL 5. Download the latest stable version. By the way I almost forgot, you can download ZF in two different assemblies:

  • Full
  • Minimal.

Full Package contains the Dojo Toolkit, and the demos to work with a skeleton. Because you are just beginning to study this framework, I recommend to download this version.

Minimal Package contains only ZendFramework library.

Extract the folder with the core (/ library / Zend), ZF is better to keep a few levels higher, so that don’t produce the files for each project, in my example, it turned out in this folder D: \ library \ ZF \ 1.7.8 \ Zend \. (i’m on PC)

Making the Structure of the Project

Let’s organize the file structure for our future project. Create two directories in the root of the application:

  • application – here all our software modules of the project will be stored
  • public, where will be available all share files.

Also create index.php and .htaccess in the root, in which immediately add rules of redirects:


RewriteEngine on
RewriteRule .* index.php

It’s necessary to add similar .htaccess file, in the folder “public”.


RewriteEngine off

Now lets create 3 folders in “application” directory: configs, library, modules.

  • configs — here is configuration files of the project.
  • library — for additional libraries.
  • modules — and it’s for modules of our application.

After all these simple manipulations I had such a structure:

The root:

  • application
  • configs
  • library
  • modules
  • public
  • .htaccess
  • .htaccess
  • index.php</li

If the structure is ready, so we can move on to the coding ;-)
Open our index file (index.php). Let the interpreter know that php code wiil start soon and determine 4 constants:


PATH_TO_ZF - the path to ZF
PATH_TO_APPLICATION - the path to the folder “application”
PATH_TO_LIBRARY - the path to our libraries
PATH_TO_MODULES - the path to our modules.

The code:

define('PATH_TO_ZF', '../../../ZF/1.7.7/');
define('PATH_TO_APPLICATION', './application/');
define('PATH_TO_LIBRARY', PATH_TO_APPLICATION . 'library/');
define('PATH_TO_MODULES', PATH_TO_APPLICATION . 'modules/');

Now we should tell our intepriter the path to load all our stuff from:

include_path(PATH_TO_ZF . PATH_SEPARATOR . PATH_TO_APPLICATION . PATH_SEPARATOR . PATH_TO_LIBRARY);

The next step is to download Zend_Loader (later we will return to it) and register classes’ autoload.

require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();

So, Zend_Loader is loaded, now let’s activate Zend_Controller_Front (about it, too, later) and point the location of our modules to the dispatcher. Then start the process of dispatching.

$controller = Zend_Controller_Front::getInstance();
$controller->addModuleDirectory(PATH_TO_MODULES)->dispatch();

The result should be something like this:

define('PATH_TO_ZF', '../../../ZF/1.7.7/');
define('PATH_TO_APPLICATION', './application/');
define('PATH_TO_LIBRARY', PATH_TO_APPLICATION . 'library/');
define('PATH_TO_MODULES', PATH_TO_APPLICATION . 'modules/');

set_include_path(PATH_TO_ZF . PATH_SEPARATOR . PATH_TO_APPLICATION . PATH_SEPARATOR . PATH_TO_LIBRARY);

require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();
$controller = Zend_Controller_Front::getInstance();
$controller->addModuleDirectory(PATH_TO_MODULES)->dispatch();

As you can notice Zend_Controller_Front never loaded because Zend_Loader loadsController automatically. Zend_Loader recognizes location of the controller on its name:
Zend_Controller_Front is in Zend/Controller/Front.php

A Little Bit More About Controller

Zend_Controller_Front implements the Singleton pattern, that means it can be initialized in the project only once. When you call a method dispatch(), the manager goes into a loop of dispatching passing three events:

  1. Routing defines what module, controller and the event can be called. If other ways are not written, then: site.ru/modules/controller/action/var1/value1/var2/value2 /. You can also override the paths through Zend_Controller_Route, but more on that in the next article.
  2. Dispatching – checking for the called module, controller, and events and call events.
  3. Answer – the view rendering.

Developing our Module

Create the folder “default” in our modules folder, it will be our first module. If we turn to our website using the link http://localhost/site.ru (you may have another location), it will be carried our default module. Name of default module can be changed, for example, to the “index”. It is done using the method – setDefaultModule (), object Zend_Controller_Front. It’s necessary to call the method before dispatching. As a parameter the method should get the module name, which will be used by default.


$controller->setDefaultModule('index');

Come on. We will create now two more folders in the module’s folder:

  • controllers — there are module controllers
  • views — but here everything related to the view (presentation)

Create a new controller (IndexController.php), and put this code:

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
return;
}
}

Now you need to create a script for our controller. For it, create folders “scripts/index” in a folder “views”. It should be something like this:


default
controllers
IndexController.php
views
scripts
index

Create a file index.phtml in the folder views/scripts/index/. Try to test it! If there are no errors, it means you are good to listen to me :) Now add the event:


$this->view->var = ‘ZendFramework’;

General view of the controller looks like this:

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$this->view->var = ‘ZendFramework’;
}
}

Lets add into the view file the following code:

echo $this->var;

After that, update the page.

Creating an Error 404 Page

Create another controller in our module, ErrorController.php:

class ErrorController extends Zend_Controller_Action
{
public function errorAction()
{
return;
}
}

Now lets create a submission for the error: /default/views/scripts/error/error.phtml:


404

In order to test it, type in your browser’s address bar: site/qwerty. As we do not have this page, so the result will be appropriate. In order that would include the output error due to which the script is stopped before dispatching we need to call the throwExceptions() method and passing the appropriate parameters, if we want to see a mistake, true, and false, if we want to differentiate a mistake when we created this page.

You’re Done!

First, I think that’s enough. For our first meeting we discussed a lot of interesting things. It is not all clear while, but do not worry. Skill comes with time. The main thing is not to be lazy and try to do something. In the article I mentioned that ZF is based on the MVC architecture. If you’re scared or have entered a dead end, the words “view”, “controller”, then launch Google and read a basis MVC theory.

That’s all; I hope you enjoyed this tutorial, and thanks for reading! See you in next chapter.

October 07 2010

06:33

Yo Yo, develop killer cross platform mobile Web apps with Jo

Dave Balmer (formerly YUI, currently working with me on webOS) has created a fantastic cross platform mobile Web framework called Jo. What do I mean by cross platform? webOS, iOS, Android, Symbian, Safari, Chrome, and even Dashboard Widgets. It's philosophy is:

If you want to jam an existing web page into an application framework, jo probably isn't for you. jo is designed to create applications. While it will play nicely with a mixture of new and old web development techniques, it uses HTML5 as a development stack and does not require direct DOM manipulation.

You can setup your views in JavaScript, or also declaratively using special tags:

HTML:
<jodialog>
    <jofieldset>
        <joinput></joinput>
        <jobutton></jobutton>
    </jofieldset>
</jodialog>
 

Take a look at the code and how it plays in action:

September 23 2010

17:19

Less Framework 2

A CSS framework for cross-device layouts Everyone writes CSS differently. Less Framework takes this into account by having a minimal set of features, and does away with things like predefined classes. All it really contains are: * a set of media-queries * typography presets aligned to a 24 px baseline grid * and a grid, [...]

View and Vote


September 22 2010

11:29

Are CSS Frameworks Evil?

CSS frameworks have a tendency to be dismissed by many CSS authors; code bloat and non-semantic class names are usually at the top of the list of reasons why. Even without ever using one, I shared the same opinion, but that might have changed after trying a few of them out while doing some research [...]

View and Vote


September 17 2010

10:00

Creating A Custom HTML and CSS Framework for Rapid Development

In this article I will go over creating a custom framework to have and use for your own projects. This to me has been one of the best resources to me in creating websites for clients. I found just like everyone else that after doing so many web pages you hit the point of realizing you keep typing the same things over and over. To try and cut down on some of the time it was taking me just to get started on a project I decided to make my own “framework” that I would use as a basic starting point. I have found this to be a great way to carry around my framework with me anywhere I go on my USB memory stick, and to be able to start a project much faster than I normally would have. Since most of my programming is done with just a basic text editor, this has worked out really well for me.

Getting Started

To start with, I am going to take a look at my own needs and see what it appears I need the most. I want to make sure then when creating my own custom HTML & CSS framework, that I include the things I use the most so it will be useful to me in the future. When starting your own I would make a simple list of the most used things you have found yourself doing over and over with each website project.

For this example I will cover the items I found myself needing the most – You can always add or remove items to better fit your own needs when making your own custom HTML and CSS framework:

1. Basic starting DOCTYPE and website head area
2. Link on the HTML document to my .CSS stylesheet
3. A good .CSS reset file
4. A starting point for my project already in place
5. A .PNG fix for older browser versions

A Basic Starting Point

For a basic starting point we will need to know the main items that will be in every website. First will be our DOCTYPE. Although this may change for some people, I know that I mostly use the same one. I got tired of trying to remember it, and it was getting old trying to copy it each time I created a website. This is a must have item within our framework.

Lets begin by creating a new file and naming it index.html – This will be the first start of our framework. Open this file and add your DOCTYPE at the beginning of the document. Since I use the XHTML strict, then I have added the following to my index.html file.

Index.html File

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

Now that we have a start of our index.html – We will continue on it by adding the HEAD section. This will be the area that we contain our meta information and link to your stylesheets in. Since I have used the same items for years, I want to make sure I include them. Adding them and leaving them blank will allow me to reuse the framework as many times as I want, and customize it each time I create a new project, but will prevent me from having to re-type it over and over every time I am creating a new website.

Now we will take a look at the other information we will be adding into our index.html file. This is the HEAD area:

Index.html

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<link rel="stylesheet" type="text/css" href="css/reset.css" media="screen" />
<link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />

<!--[if lt IE 7.]>
<script defer type="text/javascript" src="js/pngfix.js"></script>
<![endif]-->

<title></title>

</head>

Let’s take a look at everything we have added in the above code:

First is our content type, which is a must for proper document retrieval. Next is our description, keywords, and author. After these are our links to our stylesheets we will be creating (Both reset.css and style.css) – Next will be our JavaScript used to fix older browsers with the .PNG file viewing, and then all followed by our Title tag.

Adding these to the framework, and leaving the description, keywords, author and title blank – Will make it very easy to edit each time we make a new website using it.

I am going to add the following to my index.html since it is still a basic start to my every website I create. This will finish up our index.html – This will also create our BODY section of the website framework, and close out our HTML in our document.

Index.html

<body>

		<div id="wrapper">

		</div> <!-- End #wrapper -->

	</body>
</html>

Notice that I have also added a DIV for starting. This has always been my first created DIV on each website I have created unless I really needed something more specific and custom. For most generic websites this one has been a must, so I am adding it into my framework.

Here is a look at the entire Index.html file completed:

Completed Index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<link rel="stylesheet" type="text/css" href="css/reset.css" media="screen" />
<link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />

<!--[if lt IE 7.]>
<script defer type="text/javascript" src="js/pngfix.js"></script>
<![endif]-->

<title></title>

</head>
	<body>

		<div id="wrapper">

		</div> <!-- End #wrapper -->

	</body>
</html>

Next we will take a look at our .CSS files that we will be adding. Since we have already linked to these in our index.html file, we can create them now to be added to our framework. Notice also that I am using a sub-folder called css. This folder will need to be created, and our .css files will need to be added to this folder. This will help us keep files organized in our framework.

First is going to be our main stylesheet which I have named style.css – Let’s take a look at the basic of what will be added to it for styling purposes:

Style.css

html, body, div, p{
  margin: 0;
  padding: 0;
  border: 0;
  }

/* Main Layout */

body{}

#wrapper{}

/* Extras */

.clear{clear:both;}

Now for the ever so popular Eric Meyer Reset. This will be in it’s own file named reset.css and will also be added to our css folder we have created.

Reset.css

/* CSS Reset created by Eric Meyer - http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/ */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-weight: inherit;
	font-style: inherit;
	font-size: 100%;
	font-family: inherit;
	vertical-align: baseline;
}
/* remember to define focus styles! */
:focus {
	outline: 0;
}
body {
	line-height: 1;
	color: black;
	background: white;
}
ol, ul {
	list-style: none;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
	border-collapse: separate;
	border-spacing: 0;
}
caption, th, td {
	text-align: left;
	font-weight: normal;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: "";
}
blockquote, q {
	quotes: "" "";
}

Now we will need to create our JavaScript that will fix older browsers and allow them to see .PNG files correctly. I like to use PNG files when possible mainly because of the quality, but I need to keep in mind that some people still use older versions of IE which cannot properly view .PNG files. To fix this, I will make another folder and call it “js” – This folder will hold all of my JavaScript files that I would need to use on any website I am creating, but for now it will hold my pngfix.js file. Create a new file called pngfix.js and we will add the followiing:

pngfix.js

var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

if ((version >= 5.5) && (document.body.filters))
{
   for(var i=0; i<document.images.length; i++)
   {
      var img = document.images[i]
      var imgName = img.src.toUpperCase()
      if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
      {
         var imgID = (img.id) ? "id='" + img.id + "' " : ""
         var imgClass = (img.className) ? "class='" + img.className + "' " : ""
         var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
         var imgStyle = "display:inline-block;" + img.style.cssText
         if (img.align == "left") imgStyle = "float:left;" + imgStyle
         if (img.align == "right") imgStyle = "float:right;" + imgStyle
         if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
         var strNewHTML = "<span " + imgID + imgClass + imgTitle
         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
         img.outerHTML = strNewHTML
         i = i-1
      }
   }
}

This will make IE correctly display our .PNG files. We have already added the script code to our index.html file when we created it that will look for this file. Simple enough right?

Let’s move on! – Now we should have a basic setup of files that we have created that we can use as our framework. There are still a few other things that I have found that save time for me when I am creating a website so I have made sure to add them here. If you have seen my other tutorial on creating a PHP website from scratch, then you will know I frequently convert my HTML websites to PHP. To set up my framework to be readily modified to convert, I have set up my framework with the folders and files I would create when converting my HTML website. I will now add the vars folder, to place my PHP variables, and I will also add my includes folder that will have my PHP include files when and if I choose to convert the HTML to PHP.

Notice that I have also added another blank folder to my framework setup for images. This is the folder I always create and add my website images to for any project that I create. This helps organize my files when making new websites.

Here is a look at what my folder setup looks like with everything complete:

HTML CSS Framework
|
|-- index.html
|--- js
|     |-- pngfix.js
|--- images
|--- vars
|--- includes
|--- css
|     |-- style.css
|     |-- reset.css
|

A quick overview of the files we have created:

index.html – Our main html file for website creation

style.css – reset.css – Contained within our css folder, and used for styling the look of our website

pngfix.js – Our JavaScript file that fixes IE to properly view .PNG files

images folder – For adding our website images we will be using when creating the website using our framework

includes folder – For placing files we would create if converting the HTML website to PHP

vars folder – For adding variables to use with our PHP website if we converted it

PHP Notes for Conversion

For those of you that are like me and would be using this framework to make the website, then convert it to PHP – Here are some quick notes on including the PHP files, and also setting and using variables. This is just a quick reference that you can save and even keep as a txt file within your framework if you want for later use.

// Including the external PHP within XHTML
<?php include('path/filename.php') ?>

// Setting the variable itself
$variable="data details";

// Creating the output for the data
<?php
echo $variable
?>

Overall Focus

The overall focus of creating your own HTML & CSS framework is really to save time. It helps when having everything together and ready each time you want to start a new project for yourself or a client. Saving time and having some things already in place can also help with organization. Putting attention into these can sometimes help you be more creative and flexible since you would not have to waste time doing the same things over and over again. This can also help you place more attention on detail and prevent you from running your energy out on items not needed. All together this could mean the difference in yourself or a client being happy or not, and also meeting a deadline in time knowing that certain things are already done for you.

Download

If you would like to download the files that I have created within this tutorial to use for yourself in your own projects then feel free to. I have found making a simple framework is a priceless thing to have and has helped me numerous times. I do know that many of you may already have your own framework that you use but I wanted to share mine with you. Feel free to download the example tutorial files by clicking [HERE]

In Closing…

I hope everyone has enjoyed the article, and finds it useful in making your own HTML and CSS Framework. If you have any suggestions or questions then feel free to comment below and let me know. I hope that you also find it useful in your own projects and see the difference in time it takes to begin a new project. I hope it also helps everyone with creativity since you can now focus more energy into more important things such as design, and client specifics instead of starting a project from small snippets or trying to remember DOCTYPE’s – Happy coding! and thank you for reading!

August 31 2010

10:30

Raphaël 1.5 Released


Dmitry Baranovskiy and team have released another version of Raphaël, an excellent drawing and animation library backed by SVG (VML on Internet Explorer). New features in Raphaël 1.5 include custom attributes and keyframes. Keyframes can be defined similar to CSS3 Animations:

JAVASCRIPT:
el.animate({
    "20%": {cy: 200, easing: ">"},
    "40%": {cy: 100},
    "60%": {cy: 200},
    "80%": {cy: 300, callback: function () {}},
    "100%": {cy: 200}
}, 5000);
 

Check out a demo of the new keyframe animation.

Custom attributes is also a new feature that makes it easier to do things like animating a portion of an attribute segment (demo).

Full release notes:

  • fixed IE8 issue with the HTML element named Raphael
  • fixed precision for arcs in IE
  • added caching to getPointAtSegmentLength function
  • added ability to do more than one animation of an element at the same time
  • added "cubic-bezier()" as an easing method
  • added new syntax for animation (keyframes)
  • hsl2rgb now accept h as degree (0..360), s and b as % (0..100)
  • show="new" instead of target="blank" for SVG
  • added angle method
  • added snapTo method
  • cached popup || activeX for IE
  • fixed insertAfter
  • fixed timeouts for animation
  • added customAttributes

BTW I just noticed that Dmitry is now at Sencha; they're assembling quite the team! Congrats Dmitry!

August 05 2010

20:31

CodeIgniter from Scratch: Profiling, Benchmarking & Hooks


In this 15th episode of the series, we are going to learn about three subjects: Profiling, Benchmarking and Hooks. You can use these tools to analyze your CodeIgniter applications performance, and figure out what part of the code you need to optimize. We are also going to make even further improvements to the Profiler library to suit our needs.


Catch Up


Day 15: Profiling, Benchmarking & Hooks

Premium Members: Download this Video ( Must be logged in)
Day 15

Thanks for watching! Any questions/thoughts?

June 04 2010

15:46

10 Compelling Reasons to Use Zend Framework


Trying to decide which framework to use for your new project? In this article, we’ll go in-depth about why Zend Framework should absolutely be your PHP framework of choice.


Introduction

Whether you’re starting a new project or improving an existing one, in this article, I’ve provided ten reasons why you should use Zend Framework for your next project, and hopefully, it helps you in making an informed decision.


Reason 1. Extend Classes like There’s no Tomorrow

Zend Framework is a fully object-oriented framework, and as such, it utilizes a lot of object-oriented (OO) concepts like inheritance and interfaces. This makes most, if not all, of ZF’s components extendable to some point. It allows developers to implement their own special variations of individual components without having to hack into the ZF codebase itself. Being able to customize ZF this way allows you to create functionality that is unique to your project, but because of its object-oriented nature, you’ll be able to use this functionality in other projects as well.

Example

Zend Framework has a very extensive Validation component, which you can use to validate data coming from forms. In ZF, forms are treated as objects as well, and are represented by the Zend_Form component.

Let’s assume that you want to create a custom URL validator to restrict URL input from the user. The quickest way to do this would be to just validate the input using something like:

$isValid = filter_var($submitted_url, FILTER_VALIDATE_URL);

But this won’t adhere to the OO nature of form objects, since it’s not used within the context of the form. To solve this, we can create a new Zend_Validator class by extending the Zend_Validate_Abstract class:

<?php
class Zend_Validate_Url extends Zend_Validate_Abstract
{
	const INVALID_URL = 'invalidUrl';

	protected $_messageTemplates = array(
		self::INVALID_URL   => "'%value%' is not a valid URL.",
	);

	public function isValid($value)
	{
		$valueString = (string) $value;
		$this->_setValue($valueString);

		if (!Zend_Uri::check($value)) {
			$this->_error(self::INVALID_URL);
			return false;
		}
		return true;
	}
}

This actually uses the Zend_Uri class, which already has a URL checking method we can use. But since it doesn’t extend the Zend_Validate_Abstract class, we implemented a wrapping class which does implement the needed abstract class. This lets us use the Zend_Uri URL checking function in our Zend_Form objects like so:

<?php
class Form_Site extends Zend_Form
{
	public function init()
	{
		$this->setMethod('POST');
		$this->setAction('/index');

		$site= $this->createElement('text', 'siteurl');
		$site->setLabel('Site URL');
		$site->setRequired(true);

		//  Adding the custom validator here!
		$site->addValidator(new Zend_Validate_Url());
		$this->addElement($site);
		$this->addElement('submit', 'sitesubmit', array('label' => 'Submit'));
	}

}

If we wanted to check that our URLs are valid YouTube video URLs, we could do something like this:

<?php
class Zend_Validate_YouTubeUrl extends Zend_Validate_Abstract
{
	const INVALID_URL = 'invalidUrl';

	protected $_messageTemplates = array(
		self::INVALID_URL   => "'%value%' is not a valid URL.",
	);

	public function isValid($value)
	{
		$valueString = (string) $value;
		$this->_setValue($valueString);

		if (strpos($value, "http://www.youtube.com/watch?v=") !== 0) {
			$this->_error(self::INVALID_URL);
			return false;
		}
		return true;
	}
}

If we added this to our site form object as a validator, it would ensure that all URLs submitted begin with the correct YouTube video URL prefix.


Reason 2. Object-oriented Goodness


Image courtesy of http://www.developer.com

In Zend Framework, everything is an object, as proven by our example above. This poses its own disadvantages, such as making things more complicated to code. Its main advantage, though, is the ability to make code reusable, and since nobody likes to repeat themselves, this is a very good thing.

Example

We already have our Zend_Validate_Url and Form_Site class from our example above, so let’s reuse them in this example.

<?php

class IndexController extends Zend_Controller_Action
{

    public function indexAction()
    {
		$siteform = new Form_Site();

		if( $this->_request->isPost() && $siteform->isValid($this->_request->getPost()) ) {
			//stuff to do if the input is correct
			$this->_redirect("/index/correct");
		}
		$this->view->siteform = $siteform;
    }

    public function correctAction()
    {
		// Yay, we're re-using our Form_Site object!
		$this->view->siteform = new Form_Site();
    }
}

Here’s what it would look like on a browser:

If you tried to submit an invalid URL, you can see our URL validator at work:

Here, you can see what would happen if you did input a valid URL:

As you can see, we’ve never had to repeat our form object code.

“Zend_Validate classes can be used in other ways as well, not only within the context of Zend_Form classes. You simply instantiate a Zend_Validate class and call the isValid($parameter) method, passing it the value you want to validate.”


Reason 3. Use What you Need, Forget Everything Else

Image courtesy of http://dev.juokaz.com

By design, Zend Framework is simply a collection of classes. Normally, you’ll use Zend MVC components to create a fully-functional ZF project, but in any other case, you can just load the components you need. ZF is very decoupled, which means we can take advantage of the components as individual libraries, instead of the framework as a whole.

If you’ve been looking at other framework articles, you’ve probably heard of the term glue framework. ZF, by default, is a glue framework. Its decoupled nature makes it easy to use as “glue” to your already existing application.

There’s a debate between using glue frameworks vs. full-stack frameworks. Full-stack frameworks are those that provide you everything you need to create your project, like ORM implementations, code-generation, or scaffolding. Full-stack frameworks require the least amount of effort to create a project, but fall short in terms of flexibility, since it imposes strict conventions on your project.

Example

Let’s say you need a way to retrieve information about a specific video on YouTube. Zend_Gdata_Youtube is a ZF component which allows you to access data from YouTube via the GData API. Retrieving the video information is as simple as:

//Make sure you load the Zend_Gdata_Youtube class, this assume ZF is in your PHP's include_path
include_once "Zend/Gdata/Youtube.php";

$yt = new Zend_Gdata_YouTube();
// getVideoEntry takes in the YouTube video ID, which is usually the letters at the end
// of a YouTube URL e.g. http://www.youtube.com/watch?v=usJhvgWqJY4
$videoEntry = $yt->getVideoEntry('usJhvgWqJY4');
echo 'Video: ' . $videoEntry->getVideoTitle() . "<br />";
echo 'Video ID: ' . $videoEntry->getVideoId() . "<br />";
echo 'Updated: ' . $videoEntry->getUpdated() . "<br />";
echo 'Description: ' . $videoEntry->getVideoDescription() . "<br />";
echo 'Category: ' . $videoEntry->getVideoCategory() . "<br />";
echo 'Tags: ' . implode(", ", $videoEntry->getVideoTags()) . "<br />";
echo 'Watch page: ' . $videoEntry->getVideoWatchPageUrl() . "<br />";
echo 'Flash Player Url: ' . $videoEntry->getFlashPlayerUrl() . "<br />";
echo 'Duration: ' . $videoEntry->getVideoDuration() . "<br />";
echo 'View count: ' . $videoEntry->getVideoViewCount() . "<br />";

Code sample courtesy of Google Developer’s Guide

This code would output:

One thing to note here: this Zend Framework component (GData) is the official PHP library endorsed by Google to access its API. The framework’s decoupled nature allows us to use the component in any project, regardless of the framework we used to build it.


Reason 4. It lets you do a Lot of Things!

One of the things I love most about Zend Framework is that it has A LOT of components. Need a way to authenticate a user? Use Zend_Auth. Need to control access to your resources? Look up Zend_Acl. Need to create some forms? We have Zend_Form. Need to read an RSS feed? You can use Zend_Feed for that. It’s basically the Swiss Army knife of PHP classes!

Zend actually comes with some demos that show how to use its different components:

To view these, the best way is to simply download the Full Package Version of Zend Framework and test them out on your machine.

For a complete list of all the components, you can check out the Zend Framework Manual.


Reason 5. No Model Implementation – Choose your Own Adventure!

Image courtesy of http://www.vintagecomputing.com

This is actually one of the reasons most developers don’t use Zend Framework – it has no Model implementation on its own. For those who don’t know what a Model is, it’s the M in MVC, which stands for “Model-View-Controller”, a programming architecture that’s used by most PHP Frameworks.

Does that mean that Zend Framework is only a “VC” Framework?

Yes, and no.

Yes, it’s a VC framework because it doesn’t have its own Model implementation. This makes it hard for some people to use ZF, especially if they’re coming from a framework which does have a Model implementation (like CakePHP, Symfony, or even Ruby on Rails).

On the other hand, no, it’s an MVC framework as well, since apart from providing the generic ways to access the database (using Zend_Db), it actually still relies on some sort of Model implementation. What it does differently is that it leaves this kind of implementation up to the developer ñ which some say should be the case since models are actually where the business logic of the application resides, and therefore, they’re not something which can be developed as a generic component. Zend Framework Philosophy states that model implementations are unique to the projectóit’s impossible to create an abstract implementation of it since they don’t really know what you need. They believe that models should be implemented by the developers themselves.

How is this a good thing?

Not having a Model implementation means that the developer is free to use whatever means he has to implement it, or even just integrate existing implementations. Being free of predefined restraints, the developer is then allowed to create more complex implementations, rather than just simple representations of tables, which is how usual Model implementations are created. Models contain your business logic. They should not be restrained by your database tables; rather, they should dictate the connections of these tables to one another. This lets you put most of your programming code in your Models, therefore satisfying the “Thin Controllers, Fat Models” paradigm of MVC.

So how will I use Zend Framework if I have no idea how to create my own models?

For beginners, the Zend Framework Quickstart tutorial shows us a good way to implement models. In the tutorial, they implement an ORM approach to the models, wherein you would create three filesóthe actual Model, which is an abstract representation of your object; a Mapper, which maps data from the database to your Model; and a Database Table object, which is used by the mapper to get the data. You can check out the code in the ZF Quickstart tutorial, where they used this approach to implement the model of a simple Guestbook application.

For those asking “Why do I have to code this myself while other frameworks do the work for me?”, this is a perfect segue to my next reason…


Reason 6. Integrate with Whatever you Want!

Zend Framework’s decoupled nature makes it very easy to integrate other libraries that you want to use. Let’s say you want to use Smarty as your templating system. It can be done by simply creating a wrapping class for Zend_View_Abstract, which uses a Smarty instance to render the view.

This works both ways, as you can integrate ZF into other libraries as well. For example, you can integrate ZF into Symfony. They’re planning to do this with Symfony 2, using the Zend_Cache and Zend_Log components from ZF.

Example

For our example, we’ll try using Doctrine to implement our Model. Continuing from our site example above, say you’ve already implemented your DB table like so:

CREATE TABLE  `site` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `url` varchar(100) CHARACTER SET latin1 NOT NULL,
  PRIMARY KEY (`id`)
);

To integrate Doctrine into ZF, we’ll have to make sure that the proper settings are defined. I’ve followed this tutorial from dev.juokaz.com about using Doctrine with ZF.

Assuming everything works out, you’ll just have to generate your model files by running the doctrine-cli.php php file from the tutorial like so:

php doctrine-cli.php generate-models-db

You should see this success message:

Afterwards, you can check the folder which you set as the place to store the generate Model classes.

Then in our controller class, we can simply use our site model class.

<?php

class IndexController extends Zend_Controller_Action
{

    public function indexAction()
    {
		$siteform = new Form_Site();

		if( $this->_request->isPost() && $siteform->isValid($this->_request->getPost()) ) {
			//stuff to do if the input is correct
			$site = new Model_Site();
			$site->url = $this->_request->getParam('siteurl');
			$site->save();
			//redirect to our success page
			$this->_redirect("/index/correct");
		}
		$this->view->siteform = $siteform;
    }

    public function correctAction()
    {
		// Yay, we're re-using our Form_Site object!
		$this->view->siteform = new Form_Site();
    }
}

If we check our sites table, we’ll see that our records is there

Now, every time we submit a site, our controller will use our Doctrine model implementation to save to our database. Isn’t that nice and easy? Setup may be a bit complicated, but on the plus side, our project is now able to take advantage of a tool which has been developed specifically for Model implementation. Our project now has the power of two very developed technologies behind it.


Reason 7. Guidelines and Standards

Zend Framework is developed in conjunction with a very extensive Contributor Guide, which basically states that:

  1. Every contributor for both documentation and/or code, at any level (either a few lines of code, a patch, or even a new component) must sign a Contribute License Agreement (CLA).
  2. Code MUST be tested and covered by a unit test using PHPUnit. And…
  3. Code must adhere to strict Coding Standards

These strict guidelines ensure that you only use readable, high-quality code that has been tested thoroughly.


Reason 8. All Code is Guilty Until Proven Innocent (aka Test-Driven Development)

Image courtesy of http://www.codesmack.com/

Test-driven development is a programming technique that requires a developer to write tests for the function he is supposed to code before writing code for the function itself. By writing the tests first, it ensures that the programmer:

  1. Thinks of the possible use-cases of his code
  2. Creates a whitelist of input and output
  3. Makes it easier to refactor his code
  4. Makes it easier to pass code from one person to another

The test-driven development Cycle
Image courtesy of Wikipedia

Zend Framework makes it easy to do TDD via Zend_Test, which uses PHPUnit, a popular unit testing framework. PHPUnit lets you test not only your Controllers, but also your library and model functions. To add to this, Zend_Tool, which is Zend Framework’s scaffolding utility, already makes provisions for PHPUnit when you use it to create your project.

Integrating PHPUnit and Zend Framework

Setting up Zend Framework and PHPUnit is not that difficult. Basically, once you’re done with it, you’ll be able to use the same setup for your future projects. Just as a side note, the following steps assume that you’ve used Zend_Tool to scaffold your project structure and files, but it should be relatively simple to change for other setups.

First, we need to install PHPUnit. The best way is to install it via PEAR:

pear channel-discover pear.phpunit.de
pear install phpunit/PHPUnit

Afterward, we’ll open our phpunit.xml, an XML file generated by Zend_Tool. You’ll find it inside the tests folder in the root directory of your project. Add the following lines:

<phpunit bootstrap="./TestHelper.php" colors="true">
    <testsuite name="Zend Framework Unit Testing">
        <directory>.</directory>
    </testsuite>

    <filter>
        <whitelist>
            <directory suffix=".php">../library</directory>
            <directory suffix=".php">../application</directory>
            <exclude>
                <directory suffix=".phtml">../application</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>

After saving phpunit.xml, create a new file inside the same folder as phpunit.xml called TestHelper.php. This PHP file will help us setup the environment for our tests.

<?php
// start output buffering
ob_start();

// set our app paths and environments
define('BASE_PATH', realpath(dirname(__FILE__) . '/../'));
define('APPLICATION_PATH', BASE_PATH . '/application');
define('APPLICATION_ENV', 'testing');

// Include path
set_include_path(
    '.'
    . PATH_SEPARATOR . BASE_PATH . '/library'
    . PATH_SEPARATOR . get_include_path()
);

// We wanna catch all errors en strict warnings
error_reporting(E_ALL|E_STRICT);

require_once 'ControllerTestCase.php';

We then create our parent Controller Test Case class, which all of our Controllers will extend. This will help implement methods which would usually be the same throughout all of the Controller test classes.

<?php
require_once 'Zend/Application.php';
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';

abstract class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
    public $application;

    public function setUp()
    {
        $this->application = new Zend_Application(
            APPLICATION_ENV,
            APPLICATION_PATH . '/configs/application.ini'
        );

        $this->bootstrap = $this->application;
        parent::setUp();
    }

    public function tearDown()
    {
        $this->resetRequest();
        $this->resetResponse();
        parent::tearDown();
    }
}

Lastly, we create a controller test class:

<?php
require_once realpath(dirname(__FILE__) . '/../../ControllerTestCase.php');

class IndexControllerTest extends ControllerTestCase
{
    public function testCallingRootTriggersIndex()
    {
        $this->dispatch('/');
        $this->assertController('index');
        $this->assertAction('index');
    }

    public function testCallingBogusTriggersError()
    {
        $this->dispatch('/bogus');
        $this->assertController('error');
        $this->assertAction('error');
        $this->assertResponseCode(404);
    }
}

All that’s left is to run our test. Open your command prompt and go to the tests folder and type:

phpunit

Your command line should output the following:


PHPUnit and Zend Framework setup tutorial and code courtesy of http://www.dragonbe.com

Reason 9. Community and Documentation

Due to its multiple components, complexity, and fully object-oriented approach, Zend Framework has a very steep learning curve. It becomes easier to learn due to the comprehensiveness of its documentation and its thriving community. First of all, the Zend Framework Programmer’s Reference Guide boasts a complete guide to all ZF components, with examples, code, and usage theories.

Aside from this, there are a lot of blogs out there that share Zend Framework tips and tricks. For example, Phly, boy, phly, the blog of Matthew Weier O’Phinney, a Core Contributor to Zend Framework, provides a lot of insights, clever uses, and component explanations for Zend Framework. Zend also has a site called Zend Developer Zone, which aside from publishing tutorials for Zend Framework, has stuff like Zend Framework Webinars, podcasts, and articles about PHP in general. Another site, called Zend Casts, offers a lot of useful video tutorials on different Zend Framework components as well. Last but not least, there’s a free online book called Zend Framework: Surviving the Deep End” written by P·draic Brady, another Zend Framework contributor.

As you can see, there is no lack of support from the community, the documentation, and the developers. If you have any questions or need any clarifications, a quick search with the right keywords should almost always give you relevant results. If not, there’s still the Zend Framework Mailing Lists, the official Zend Framework Forums, the unofficial Zend Framework Forums or the unofficial Zend Framework IRC channel


Reason 10. Certifications Ahoy!

If you’re still unconvinced about learning and using Zend Framework, this reason is actually the one that I feel most distinguishes Zend Framework from all the others. Zend not only offers Zend Framework Certification, but PHP Certification as well. By offering certifications, Zend helps you use your expertise in PHP and Zend Framework to boost your portfolio or CV. The Zend Certification site lists a number of reasons to get certified, some of which are:

  1. Differentiate yourself from competitors when looking for a new job
  2. Get your resume/CV noticed
  3. Have your profile displayed in Zend’s Yellow Pages for PHP Professionals
  4. Be part of the Linkedin Group Exclusively for ZCE’s
  5. Get special discounts on Zend PHP conferences worldwide

Addendum

Just to keep things balanced, here’s a quick list of reasons why you might not want to use Zend Framework:

  1. VERY steep learning curve. It’s not very hard for advanced PHP users, but for beginners, there’s a lot to learn!
  2. Big footprint. Since Zend Framework has a lot of components, it’s total size is relatively higher than other Frameworks. For example, CodeIgniter’s system folder has a 1.5MB footprint compared to Zend Framework’s 28MB footprint.
  3. No solid scaffolding tool. Although Zend_Tool offers some functionality, it’s not much compared with the scaffolding utilities of full-stack frameworks like CakePHP or Symfony.
  4. Not shared webhosting friendly. The folder structure generated by Zend_Tool suggests that the public folder be the only directory accessible via http ó which assumes that a user is able to create a virtual host for the project. This is something you aren’t able to do in most shared web hosting environments.
  5. Too gluey. Since everything is in separate classes, it’s sometimes hard to envision how everything works. This wouldn’t be a problem with full-stack frameworks, since they mostly take care of everything for you. Without Zend_Tool, it would be extremely difficult to set up a working project structure

Conclusion

A lot of advancements have been made in the world of PHP Frameworks in the past few years. I’ll be honest, there’s a whole lot of fish in the sea. There are frameworks like Codeigniter, CakePHPand Symfony which are also good to use. Some of you might be thinking, “Why did this guy focus on Zend Framework? Why didn’t he run performance tests to compare the different frameworks?” To that, I reply with this quote from a very entertaining article entitled “PHP Framework Benchmarks: Entertaining But Ultimately Useless” by P·draic Brady:

To create a positive benchmark, you need to understand that all frameworks were born as festering piles of unoptimised stinking crap. They were all born bad and get worse with age. This sounds quite sad, but actually it’s an inevitable compromise between performance and features. It’s also a compromise between performance and ease-of-use. So you see, performance is unfairly faced by two opponents: features and ease-of-use. All performance is sacrificed in the name of serving the needs of rapid development, flexibility, prototyping, and making your source code look prettier than the other guy’s. As if.

What happens if you move away from the enemies of performance and do some propping up behind the scenes? You get…wait for it…oodles of extra performance!

When it comes down to it, which framework you choose to use really depends on how comfortable you are with it. None of these frameworks would be of help to you if you aren’t able to take full advantage of their features. You can spend weeks or even months using a specific framework, only to trash it in the end because you just aren’t as comfortable using it as you were with some other framework.

So I invite you to at least try out Zend. If it works for you, that’s great! It does for me. But if it’s not a good fit, go ahead and try out the others. Soon enough, you’ll find the framework that’s just right for your needs.

May 19 2010

18:12

2010: Web Fonts Are Here and Ready to Use


There's an old saying: "It took me ten years to be an overnight success." We've been waiting for web fonts for at least a decade, and 2010 will finally be the year that web fonts go mainstream.

This is in no small part to the work both Typekit and Google have been doing. Today they both announced some very cool things in this area.

First up, Google announced that they are releasing high quality open source fonts in the Google Font Directory. Since these are open source you can even download the original font files yourself at the font code.google.com project.

Next, Google has made it very easy to include these fonts into your page using the new Google Font API. To use a font you simply drop some HTML into your page similar to the following, specifying the font you want to use:

HTML:
<link href='http://fonts.googleapis.com/css?family=Tangerine'
      rel='stylesheet'
      type='text/css'>

body { font-family: 'Tangerine', serif; }

Doesn't get simpler than that. The new API does alot of things for you behind the scenes:

Google’s serving infrastructure takes care of converting the font into a format compatible with any modern browser (including Internet Explorer 6 and up), sends just the styles and weights you select, and the font files and CSS are tuned and optimized for web serving. For example, cache headers are set to maximize the likelihood that the fonts will be served from the browser’s cache with no need for a network roundtrip, even when the same font is linked from different websites.

These fonts also work well with CSS3 and HTML5 styling, including drop shadows, rotation, etc. In addition, selecting these fonts in your CSS works just the same as for locally installed fonts, facilitating clean separation of content and presentation.

On a related front, Typekit and Google announced a new Web Font Loader that smooths over many of the differences around loading web fonts on a page:

The WebFont Loader puts the developer in control of how web fonts are handled by various browsers. The API fires JavaScript events at certain points, for example when the web font completes downloading. With these events, developers can control how web fonts behave on a site so that they download consistently across all browsers. In addition, developers can set the fallback font's size to more closely match the web font, so content doesn't reflow after loading.

Furthermore, the WebFont Loader is designed to make it easy to switch between different providers of web fonts, including Google, Typekit, and others. The code is modular, and we expect to add modules for other major web font providers in coming weeks.

It's great to see Typekit involved in this; they are a real pioneer in this area and have helped make fonts on the web a reality.

To see all these pieces together navigate over to Smashing Magazine which relaunched their site using these technologies.

Congrats to the Google Web Fonts and Themes team, including Raph Levien, Jeremie Lenfant-Engelmann, Marc Tobias Kunisch, Meslissa Louie, and David Kuettel.

[Disclosure: I work for Google and know the Web Fonts team. However, even if I didn't, I would still be excited about this since I've been waiting for web fonts to happen since the 90s!]

March 25 2010

18:30

CodeIgniter from Scratch: Shopping Cart

Today, we are going to take a look at the Shopping Cart library for CodeIgniter. This useful class allows us to add and remove items to a shopping cart, update them, and calculate prices. I will demonstrate how you can build a simple shopping cart system with the help of this library..


Catch Up


Day 12: Shopping Cart

Final Project


February 04 2010

13:47

Working with RESTful Services in CodeIgniter

CodeIgniter is becoming well known for its power as a PHP based web application framework, but it’s not often we see examples of it being used for anything else. Today we’ll learn how we can use CodeIgniter to create a RESTful API for your existing web applications and demonstrate how to interact with your own API or other RESTful web-services such as Facebook and Twitter.

Tutorial Details

Introduction

If you have been following the CodeIgniter From Scratch series you will know by now that it is relatively quick and easy to put together simple web applications, such as blogs, CMS systems, brochure sites, etc. One thing you may not have thought about is using CodeIgniter to create an interactive API. After trying several existing REST implementations, I found they not only lacked simplicity but were missing most of the features you would expect from a RESTful implementation; so I built my own. This tutorial will show you how to use this code to set up your REST API, and gives example of how to interact with it from your web application.

Assumptions

  1. You have a web server set up, locally or online and known how to manage files on it.
  2. You have read a few of the CodeIgniter from Scratch tutorials.
  3. You know how to set up CodeIgniter.
  4. You know a little about RESTful services.

This tutorial is broken down into two parts. We will start by learning how to create a RESTful service, then further down we will learn how to interact with it in a few different ways.

Part 1 – Creating a RESTful API

Step 1: Setting up the Demo

Firstly you need to download the codeigniter-restserver code from GitHub and extract it and move the code to your server.

When you open the folder, you will see an entire CodeIgniter install, which is there to power the demo. This allows people to have a play with the REST demo before integrating with your existing application.

Open up “application/config/config.php” and set the base_url to get links working. This base_url will be different for everyone and depends entirely on where you uploaded your files.

Step 2: The URLs

With the files extracted and the base_url set, we are ready to load up our RESTful CodeIgniter install and have a look at the demo supplied with it. Browse the base URL, which by default is:

http://localhost/restserver

Here you will find a few example links to the example_api controller which can be found at “application/controllers/example_api.php”. Let’s disect the URL’s of these examples to see what is going on. The first URL is a very simple one.

This URL looks very much like any other CodeIgniter URL with a controller and a method, but you will notice in this diagram the method is named a “Resource”. REST is all about Resources and they are essentially a noun within your application, which are interacted with (i.e added, deleted, edited, queried) based on HTTP headers and URL query strings or HTTP arguments.

The default format for output is XML which is what we see in this basic example. The other links are slightly larger and demonstrate how to pass parameters and show how the output format can be modified in the URL:

Normally in CodeIgniter you just pass in parameter values, but a REST controller accepts any number of parameters in any order. For this to work, we need to pass in the name of the parameter followed by the value in pairs.

At the end of the URL is the “format” parameter. This is a reserved parameter that will modify the output format of the requested data like so:

By giving both the API developer and the client application the choice of data formats to use, the API is opened up to a much wider audience and can be used with more programming languages and systems. These three are not the only formats supported, out of the box your REST API can use:

  • xml – almost any programming language can read XML
  • json – useful for JavaScript and increasingly PHP apps.
  • csv – open with spreadsheet programs
  • html – a simple HTML table
  • php – Representation of PHP code that can be eval()’ed
  • serialize – Serialized data that can be unserialized in PHP

While adding the format to the URL is not technically the most RESTful way to change formats, it allows for easy browser testing and lets developers without cURL perform simple GET requests on the API. The more RESTful way is to send a Content-type HTTP header to the REST controller using cURL, but that will be explained later.

Step 3: The Code

Now if you open up application/controllers/example_api.php you will immediatley spot a few differences from normal CodeIgniter controllers.

REST_Controller

In the MVC pattern, a controller is the central point of the logic. It is called when a user makes a request and then based on the logic in the controller it fetches data and outputs views. CodeIgniter contains its own logic for how a Controller should work, but as we are doing something different we need our own REST_Controller library to contain its own REST related logic. So instead of simply using:

<?php
class Example_api extends Controller {

}

…you will need to use:

<?php
require(APPPATH'.libraries/REST_Controller.php');

class Example_api extends REST_Controller {

}

Working with Resources

Now your empty controller is set up, next are the methods or “resources”. This is prossibly the most confusing part of the tutorial if you are used to how CodeIgniter works. Basically, you take the Resource and the HTTP verb and combine them to make a method name. So the two examples we looked at before had a Resource of user and users. Because both of these were loaded in the browser, we know it was using a GET request and so the two methods below are used:

<?php
require(APPPATH'.libraries/REST_Controller.php');

class Example_api extends REST_Controller {

    function user_get()
    {
		// respond with information about a user
    }

    function users_get()
    {
		// respond with information about several users
    }
}

This may seem a little strange, but it gives you the ability to use the same URL and respond to the request depending on the HTTP verb that has been used. If somebody tries to access your API in a way that is not allowed (in this example PUT or DELETE) it will simply respond with a 404. If you aren’t sure about HTTP verbs, let me explain.

GET

Used to fetch information about an existing resource. This is used by browsers when you enter a URL and hit go, or when you click on a link, so it perfect for fetching information on one of your REST resources (like user).

POST

Used to update an existing resource with information. Browsers use this to submit most types of forms on the internet, although some use GET as well by submitting the form action with a query string containing the field data.

PUT

Less commonly used and not supported by most browsers, PUT is used to create a new resource.

DELETE

Also not used by many browsers, this HTTP verb rather obviously is used to delete a resource.

If we put that into code and allow each verb on the resource user it would look like this:

<?php
require(APPPATH'.libraries/REST_Controller.php');

class Example_api extends REST_Controller {

    function user_get()
    {
		// respond with information about a user
    }

    function user_put()
    {
		// create a new user and respond with a status/errors
    }

    function user_post()
    {
		// update an existing user and respond with a status/errors
    }

    function user_delete()
    {
		// delete a user and respond with a status/errors
    }
}

Accessing parameters and returning data

SO now the API has been given its structure by setting up the resources and defining a method for each HTTP verb we wish to support, we need parameters so we can use our CodeIgniter models and libraries. This is one of the major benefits of using CodeIgniter for our API, as we can use our existing models and libraries and not have to re-code them.

<?php
require(APPPATH'.libraries/REST_Controller.php');

class Example_api extends REST_Controller {

    function user_get()
    {
		$data = array('returned: '. $this->get('id'));
		$this->response($data);
    }

    function user_post()
    {
		$data = array('returned: '. $this->post('id'));
		$this->response($data);
    }

    function user_put()
    {
		$data = array('returned: '. $this->put('id'));
		$this->response($data;
    }

    function user_delete()
    {
		$data = array('returned: '. $this->delete('id'));
		$this->response($data);
    }
}

This example contains five new pieces of code:

$this->get()

Is used to return GET variables from either a query string like this index.php/example_api/user?id=1 or can be set in the more CodeIgniter’esque way with index.php/example_api/user/id/1.

$this->post()

Is an alias for $this->input->post() which is CodeIgniter’s method to access $_POST variables with XSS protection.

$this->put()

Reads in PUT arguments set in the HTTP headers or via cURL.

$this->delete()

You guessed it, this reads in DELETE arguments, also set in HTTP headers or via cURL.

$this->response()

Sends data to the browser in whichever data format has been requested, or defaults to XML. You can optionally pass a HTTP status code to show it has worked or failed. E.g if the ID provided was not in the database, you could use $this->response(array(‘error’ => ‘User not found.’), 404);

Step 4: Working with your Models

Until now we have been working with an example API in a clean install, so the next step is to get a REST API running from your existing codebase.

Although the download comes with a full CodeIgniter installation for the demo and to allow API’s to be built from scratch, the only two files of importance are:

  1. application/config/rest.php
  2. application/libraries/REST_Controller.php

Drop those two files into your CodeIgniter application and create a new API controller.

<?php
require(APPPATH.'/libraries/REST_Controller.php');

class Api extends REST_Controller
{
	function user_get()
    {
        if(!$this->get('id'))
        {
        	$this->response(NULL, 400);
        }

        $user = $this->user_model->get( $this->get('id') );

        if($user)
        {
            $this->response($user, 200); // 200 being the HTTP response code
        }

        else
        {
            $this->response(NULL, 404);
        }
    }

    function user_post()
    {
        $result = $this->user_model->update( $this->post('id'), array(
        	'name' => $this->post('name'),
        	'email' => $this->post('email')
        ));

        if($result === FALSE)
        {
        	$this->response(array('status' => 'failed'));
        }

        else
        {
        	$this->response(array('status' => 'success'));
        }

    }

    function users_get()
    {
        $users = $this->user_model->get_all();

        if($users)
        {
            $this->response($users, 200);
        }

        else
        {
            $this->response(NULL, 404);
        }
    }
}
?>

This shows an example API with some generic model names. In the first method we are picking up a ?id=XX and passing it to the model. If data is found we send it to the $this->response() function with a status 200. If nothing is found, return no body and a 404 to say nothing was found. You can imagine how this could be expanded to run all sorts of API activities for your web application.

Step 5: Securing the API

Now your API is built it needs securing so only users given access can interact with the API. To set the login type, usernames and passwords open up “application/config/rest.php” inside your codebase.

/*
|--------------------------------------------------------------------------
| REST Login
|--------------------------------------------------------------------------
|
| Is login required and if so, which type of login?
|
|	'' = no login required, 'basic' = relatively secure login, 'digest' = secure login
|
*/
$config['rest_auth'] = 'basic';

None

Anyone can interact with any one of of your API controllers.

Basic

A relatively insecure login method which should only be used on internal/secure networks.

Digest

A much more secure login method which encrypts usernames and password. If you wish to have a protected API which anyone could get at, use digest.

/*
|--------------------------------------------------------------------------
| REST Login usernames
|--------------------------------------------------------------------------
|
| Array of usernames and passwords for login
|
|	array('admin' => '1234')
|
*/
$config['rest_valid_logins'] = array('admin' => '1234');

Setting up the users is simple. Each login is an array item, with a key and a value. The key is the username and the value is the password. Add as many as you like to this array and dish them out to anyone who will be using the API.

Part 2 – Interacting with RESTful Services

Wether it is the API you have just buit or a public service such as Twitter, you will want to be able to interact with it somehow. Seeing as RESTful services work with basic HTTP requests it is very easy to do this in a number of different ways.

Different Methods to Interact with REST

Each of these different interaction methods will be shown with the code placed directly in Controller methods. This is purely so the demos are easier to read and would normally would be placed inside a model or a library for correct MVC separation.

file_get_contents()

Using the very simple PHP function file_get_contents(), you can perform a basic GET request. This is the most basic of all the methods but is worth mentioning for those “quick and dirty” moments.

$user = json_decode(
	file_get_contents('http://example.com/index.php/api/user/id/1/format/json')
);

echo $user->name;

Worth noting is that, while this method will not work using HTTP Digest authentication, if you are using HTTP Basic authentication you can use the following syntax to get data from your password protected RESTful API:

$user = json_decode(
	file_get_contents('http://admin:1234@example.com/index.php/api/user/id/1/format/json')
);

echo $user->name;

There are a few problems to using this method: the only way to set extra HTTP headers is to set them manually using the PHP function stream_context_create() which can be very complicated for developers new to the internal workings of HTTP requests. Another disadvantage is you only receive the body of the HTTP response in its raw format, which means you need to handle conversion from very single request.

cURL

cURL is the most flexible way to interact with a REST API as it was designed for exactly this sort of thing. You can set HTTP headers, HTTP parameters and plenty more. Here is an example of how to update a user with our example_api and cURL to make a POST request:


    function native_curl($new_name, $new_email)
    {
	    $username = 'admin';
		$password = '1234';

		// Alternative JSON version
		// $url = 'http://twitter.com/statuses/update.json';
		// Set up and execute the curl process
		$curl_handle = curl_init();
		curl_setopt($curl_handle, CURLOPT_URL, 'http://localhost/restserver/index.php/example_api/user/id/1/format/json');
		curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl_handle, CURLOPT_POST, 1);
		curl_setopt($curl_handle, CURLOPT_POSTFIELDS, array(
			'name' => $new_name,
			'email' => $new_email
		));

		// Optional, delete this line if your API is open
		curl_setopt($curl_handle, CURLOPT_USERPWD, $username . ':' . $password);

		$buffer = curl_exec($curl_handle);
		curl_close($curl_handle);

		$result = json_decode($buffer);

		if(isset($result->status) && $result->status == 'success')
		{
			echo 'User has been updated.';
		}

		else
		{
			echo 'Something has gone wrong';
		}
    }

Interacting with your API this way works fine but there are two problems with this method:

  1. It uses an ugly confusing syntax – imagine creating several an application based on that.
  2. cURL is not installed on all servers by default.

To solve this ugly syntax, a cURL library has been developed for CodeIgniter which simplifies things immensely.

The exact same request made with the cURL library would look like this:

    function ci_curl($new_name, $new_email)
    {
	    $username = 'admin';
		$password = '1234';

		$this->load->library('curl');

		$this->curl->create('http://localhost/restserver/index.php/example_api/user/id/1/format/json');

		// Optional, delete this line if your API is open
		$this->curl->http_login($username, $password);

		$this->curl->post(array(
			'name' => $new_name,
			'email' => $new_email
		));

		$result = json_decode($this->curl->execute());

		if(isset($result->status) && $result->status == 'success')
		{
			echo 'User has been updated.';
		}

		else
		{
			echo 'Something has gone wrong';
		}
    }

Much nicer to look at right? Well there is an even easier method to work with REST in your CodeIgniter applications that this.

REST client library

A REST client library has been developed that sits on top of this cURL library which handles format conversion, HTTP logins and several other aspects of your REST API.

    function rest_client_example($id)
    {
		$this->load->library('rest', array(
			'server' => 'http://localhost/restserver/index.php/example_api/',
			'http_user' => 'admin',
			'http_pass' => '1234',
			'http_auth' => 'basic' // or 'digest'
		));

        $user = $this->rest->get('user', array('id' => $id), 'json');

        echo $user->name;
    }

Here you can see we are making a GET request, sending id as a parameter and telling the library we want ‘json’ as the content format. This handles the setting of Content-type for you, and converts the data into a PHP object for you. You can change this value to ‘xml’, ‘json’, ’serialize’, ‘php’, ‘csv’ or any custom MIME-type you like, for example:

	$user = $this->rest->get('user', array('id' => $id), 'application/json');

As you have probably guessed as well as $this->rest->get(), the library also supports $this->rest->post(), $this->rest->put(), $this->rest->delete() to match all of your REST_Controller methods.

You will need to var_dump() results coming from the REST client library to make sure you are getting the right data format back. The conversion will somtimes be array and sometimes be an object, depending on how it is converted by PHP. If the returned MIME-type is not supported then it will simply return the format as plain-text.

Talking to Twitter

Using this REST library you can talk other RESTful services such as Twitter and Facebook. Here is a simple example of how you can get details for a specfic user based on their ID, using Twitter’s default format XML.

        $this->load->library('rest', array('server' => 'http://twitter.com/'));

        $user = $this->rest->get('users/show', array('screen_name' => 'philsturgeon'));
        $this->load->library('rest', array(
        	'server' => 'http://twitter.com/',
			'http_user' => 'username',
			'http_pass' => 'password',
			'http_auth' => 'basic'
        ));

        $user = $this->rest->post('statuses/update.json', array('status' => 'Using the REST client to do stuff'));

Looking at this, you will notice that interacting with the Twitter API is a bit different in a few ways.

  1. They support URL based format switching in the form of .json instead of /format/json. Some require an extention, some do not so it’s best to always add them on.
  2. They mostly only support GET/POST, but are starting to add more DELETE methods
  3. They dont always have just a resource in their URL, for example: users/search is one REST method, but lists is another.

Keep an eye out for these differences as they can catch you out. If you get stuck, simply echo $this->rest->debug() for a whole range of information on your REST request.

Summary

Combining what you now know about RESTful services, the CodeIgniter REST client library and the Twitter API documentation – or any other RESTful API documentation for that matter – you can create some very powerful applications that integrate with any custom or public web service using REST. You can extend your API by creating more REST_Controller’s and even make a modular API by using Matchbox or Modular Separation to create an api.php controller for each module to help keep your API as neatly organized as your application.

Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at nettuts@tutsplus.com.

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Write a PLUS tutorial


Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.
(PRO)
No Soup for you

Don't be the product, buy the product!

close
YES, I want to SOUP ●UP for ...