Titon

For the past few years I've been working on a project called Titon — a PHP framework and a front-end library built on MooTools. Titon refers to anything back-end related as the "Framework", while anything front-end related as the "Toolkit". The Framework isn't full-stack in the modern sense, it's simply a collection of packages that can be installed through Composer. The Toolkit is a collection of modular UI classes and helpers written in HTML5, CSS3, Sass and MooTools 1.4.

A brief history

I started writing Titon back in September 2009, around the same time PHP 5.3 was released. The idea behind Titon was simply a learning lesson. It gave me a chance to learn namespaces, closures and all the new PHP functionality. It also permitted me to write systems I would never really write, like database abstraction layers, object relational mappers, caching and storage engines, internationalization and localization, routing, so on and so forth. It was also a great learning lesson on how to properly use interfaces and abstraction classes, while also practicing design patterns and improving with design principles like DRY, KISS, YAGNI, and many others.

Over the course of 3 years, the Titon codebase evolved into a fully fledged framework (albeit not 100% runnable). The architecture was rewritten about 3-4 times as I would try new, different and unique approaches. Classes and interfaces came and went. Functionality was stripped (YAGNI) or dumbed down (KISS). Features were completed or backlogged. Roadmaps were created and abruptly forgotten about. Writing a full-stack framework took time and eventually I stopped working on it many months at a time.

It was around 2012 when I jumped back onto Titon. With the recent release of PHP 5.4 and the ever increasing usage of Composer, it felt like the perfect time. Instead of building a full-stack framework (because do we really need another framework) like before, I decided to break it down into multiple smaller packages that can be installed through the Composer. This would encourage usability, promote decoupling and not require a developer to use a heavy framework for certain functionality. Over the course of the next year, I broke it down into 15 primary packages and 4 supporting packages.

Why am I releasing it?

Even though it was a learning lesson, these packages could still be beneficial to someone (or even you), hence the release. I don't expect Titon to compete with Symfony, CakePHP, Zend, or the many other frameworks, nor do I care. If a packages solves a problem you have, then perfect, go ahead and use it! If a package or Titon as a whole is never used, I won't mind either way. In the end, it taught me everything I currently know, and I couldn't be happier.

What are the Framework packages?

Like previously mentioned, Titon is decoupled into 15 primary packages and 4 supporting packages. A primary package is a collection of classes that provide functionality for a specific feature, for example, a model layer, route mapper, or caching engine. A supporting package is an optional dependency for primary packages that include additional functionality, for example, the MySQL driver for the Model package.

The following packages are available, fully functional and tested. They are split between PHP 5.3 and 5.4, as there was no reason to limit simplistic packages to 5.4 only.

PHP 5.3
  • Debug - Provides logging, debugging and advanced error and exception handling
  • Environment - Allows for multiple environment configuration and bootstrapping
  • Event - Notifies a list of objects during an event and allows for listener registration
  • Type - Implements class like functionality for arrays, strings, objects and enums
  • Utility - Provides convenience classes for basic tasks like validation, formatting, sanitization and more
PHP 5.4
  • Cache - Provides a data caching layer that supports multiple storage engines
  • Common - Provides global functionality like class traits and augmentation as well as dependency and configuration management
  • Controller - Provides controllers that handle the HTTP dispatch cycle and are loosely coupled with other packages
  • G11n - Implements localization and internationalization through message and locale bundles
  • HTTP - Provides classes for interacting with sessions, cookies and the request and response
  • IO - Permits file system manipulation through readers, writers and resource bundles
  • Model - Implements a lightweight database abstraction layer and an object relational mapper
    • MySQL - Enables the MySQL database driver
    • PostgreSQL - Enables the PostgreSQL database driver
    • SQLite - Enables the SQLite database driver
    • MongoDB - Enables the MongoDB database driver
  • MVC - Bundles the Model, View and Controller packages while adding support for dispatching and modularization
  • Route - Provides dynamic route handling, matching and mapping
  • View - Allows for template look-up and rendering through engines and helpers
What about the Toolkit?

The Toolkit is a collection of JavaScript classes and CSS modules known as components. Each component provides front-end functionality, like modals, tooltips and buttons. But doesn't this compete with Twitter bootstrap? In a sense yes, however, there are some major differences. The first being that Toolkit uses MooTools instead of jQuery (if you're one of the rare developers like me who don't like jQuery). The second being that Toolkit doesn't provide default styles like Bootstrap, it merely provides the functionality. This allows the developer – you – to integrate and customize the components at will.

The following components are currently available. Each component is either purely CSS or a combination of CSS and JavaScript.

JavaScript
  • Accordion - Provides collapsible support to a list of sections
  • Blackout - Displays a transparent black element over the document
  • Cache - Provides local and session storage within the class layer
  • Flyout - Displays nested flyout menus that appear below an element that activates it
  • LazyLoad - Provides an easy way to lazy-load images (inline and background) while scrolling
  • Modal - Displays dynamic modals that will display above the content
  • Pin - Pin an element in a container that stays within the viewport while scrolling
  • Popover - Displays dynamic notification elements over an element
  • Tabs - Provides tabbed support to an element containing navigation tabs and sections
  • Timers - Provides timer and interval management within the class layer
  • Tooltip - Displays dynamic tooltips over an element or the mouse cursor
  • TypeAhead - Displays a list of possible options below an input while typing
CSS
  • Animations - CSS3 transitions for specific animations: fade, slide, etc
  • Alert - Styles for block level notification messages
  • Button - Styles for generic cross-browser compatible buttons
  • ButtonGroup - Allows for the grouping of multiple buttons into 1 visual styled button
  • Icon - Allows for inline image sprites to be used at 12, 16, 24, 32, and 64 sizes
  • Label - Styles for inline tag labels
  • Badge - Styles for inline notification bubbles
  • Pagination - Styles for pagination lists
  • Visual - Provides visual aesthetics like gloss and glare over elements
What about a full application?

Nothing is stopping you from using Titon as a full application — hell, even the MVC package was built for this purpose. Since Titon is a collection of packages, there's no set guidelines on how to build an application, it's all up to how you want to piece it together. However, to make things easier, I've thrown together a skeleton application that you may use as a base.

What does the future hold?

In regards to the Framework, I have no plans to add anymore primary packages. I do have plans to add minor supporting packages, like Smarty and Twig support for the View layer. Any bugs, issues or feature requests I will handle of course. I would also like to increase unit testing and average around 90% code coverage for all packages.

The Toolkit however will receive full support and the inclusion of many more components. I currently use Toolkit on all my personal websites.

In the off chance that Titon becomes popular, I will provide in-depth documentation, a fully functional website, and reverse my decision on new packages.

How can you start using it?

By installing through Composer, or cloning the repository, or downloading the project. Since no official website exists, nor does any documentation, learning how to use each package can be tricky. Each repository contains a docs folder that provides basic documentation on each class in the repo. For any functionality that is not documented, I highly suggested reading the source code and its comments. And if no documentation exists for a specific class, let me know and I will provide one.

Using Toolkit requires some manual intervention as the source files need to be compiled. This allows for custom Toolkit builds (only requiring certain components) to be generated through Grunt. Instructions on how to do this can be found in the repository.

I will also be blogging about each package and how to use it, so expect those in the near future!

The end of the HtmlHelper

For the past two years, I have gotten pretty close with the HtmlHelper. It has been there for me, making my life easier than before. But that time has come to an end, so sorry HtmlHelper, you are just too much of a burden now a days. The HtmlHelper has been an amazing convenience by automatically building my anchor links, by creating images with the correct path, or linking my CSS from within separate views, and much much more. But why do all this when you can simply write the HTML yourself?

I am not sure why I didn't notice this sooner; I was probably just stoked on developing with CakePHP so I wanted to do everything the CakePHP way. Lately however, I have noticed that the HtmlHelper really isn't needed that much. I can only think of a few cases where it is needed: linking stylesheets/javascript dynamically, building breadcrumbs and creating routes. Everything else is just consuming PHP logic and processing time to render HTML, which you can simply write yourself in the first place and bypass the PHP interpreter.

Linking Routes

The primary use of the helper, but why not just use url() instead? By doing that you don't have to deal with the hassle of nesting your array of attributes, or escaping variables into the method call. You also don't have to worry about Cake being over zealous and escaping all your data. Take these examples, they deliver the same result.

// With the helper
<?php echo $this->Html->link('Anchor Link', array('controller' => 'news', 'action' => 'index'), array('title' => 'Anchor Title')); ?>
// Without the helper
<a href="<?php echo $this->Html->url(array('controller' => 'news', 'action' => 'index')); ?>" title="Anchor Title">Anchor Link</a>
// Or pure HTML if your routes never change
<a href="/news" title="Anchor Title">Anchor Link</a>
Doctypes and meta tags

Another example of using PHP to render HTML, when you can just write HTML. This gets even easier with HTML5.

<?php echo $html->docType('xhtml-trans');
echo $html->meta('keywords', 'miles johnson php mysql design code developement developer web production creation coding functions tutorials methods scripts packages open source cakephp cake bake controller component model behavior view helper'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<meta name="keywords" content="miles johnson php mysql design code developement developer web production creation coding functions tutorials methods scripts packages open source cakephp cake bake controller component model behavior view helper" />
Images

This one I am still 50/50 on. It helps by determining the base URL, detecting asset timestamps and appending the alt attribute. But this of course can still be written normally as well. I will let you decide.

<?php echo $this->Html->image('logo.png'); ?>
<img src="/img/logo.png" alt="" />
Divs, paragraphs, tables, lists, script blocks

All of these should never be used in the view or layout. Using PHP to render basic HTML tags like this is absurd in my opinion.

So when should the helper be used?

Like I stated above, there are only a few times when the helper should be used. The first is asset linking (stylesheets and javascript). This allows you to include an asset from within any view, which is then output within $scripts_for_layout. Why is this so awesome? Simple, you can have a specific stylesheet for a specific page, without having to include it on all pages.

Secondly is building breadcrumbs. From within your view you can define the "top level" or "trailing" crumb, and within your layout you can define the base crumbs. This allows you to add multiple levels of crumbs within different layers of views. A quick example, which would give you the trail of: Blog -> Archives -> Blog Title.

// In the view
$this->Html->addCrumb('Archive', array('controller' => 'blog', 'action' => 'archive');
$this->Html->addCrumb($blog['Blog']['title'], array('controller' => 'blog', 'action' => 'read', $blog['Blog']['id']);
// In the layout
$this->Html->addCrumb('Blog', array('controller' => 'blog', 'action' => 'index');

Lastly, the primary reason that the HtmlHelper has all these convenience methods, is so that you can use them within other helpers. Since it's impossible to render HTML within PHP without string concatenation, the HtmlHelper gives other helpers the ability to render HTML easily without all the hardship. That is the primary reason of this helper.

Now all of this is a personal opinion of course, but since I didn't realize most of this for a while, I thought some of you might not have either. This is neither belittling the CakePHP dev team as they have done an awesome job so far, so thank you! So take it how you wish and code how you like. Enjoy!

Stripping HTML automatically from your data

About a week ago I talked about automatically sanitizing your data before its saved. Now I want to talk about automatically stripping HTML from your data before its saved, which is good practice. Personally, I hate saving any type of HTML to a database, thats why I prefer a BB code type system for this website. To strip all tags from your data, add this method to your AppModel.

/**
 * Strip all html tags from an array
 *
 * @param array $data
 * @return array
 */
public function cleanHtml($data) {
	if (is_array($data)) {
		foreach ($data as $key => $var) {
			$data[$key] = $this->cleanHtml($var);
		}
	} else {
		$data = Sanitize::html($data, true);
	}
	return $data;
}

Pretty simple right? The next and final step is to add it to AppModel::beforeSave(). In the next example, I will use the code snippet from my previous related article. Once you have done this your are finished, now go give it a test drive.

function beforeSave() {
	if (!empty($this->data) && $this->cleanData === true) {
		$connection = (!empty($this->useDbConfig)) ? $this->useDbConfig : 'default';
		$this->data = Sanitize::clean($this->data, array('connection' => $connection, 'escape' => false));
		$this->data = $this->cleanHtml($this->data);
	}
	return true;
}