Archive for the ‘Nerd Matrix’ Category
MEET THE AUTEUR
This marks the second installment of our continuing series on the presentations made during our weekly Lifeblue University sessions. LB University gives the members of Lifeblue the opportunity to practice their presentation skills by sharing their expert knowledge on a topic of their choice. Providing each other with knowledge and insight on different subjects expands our breadth of knowledge as professionals and people and builds us to be more T-shaped thinkers. Through creating an environment of continuous learning and enrichment, LB University is one of the ways we support our ideology of combining creative and technology. With these blog entries, we want to pass what we learn in these intriguing presentations on to you.
Recently LB’s Jonathan Pacheco gave a presentation on the “Auteur Theory” and how this idea can be applied to the world of web development and design. According to Jonathan, the Auteur Theory originates in film criticism, stating the belief that a film reflects the director’s personal creative vision, as if they were the primary “auteur” (French for “author”).
Opposition of this theory holds that a film isn’t just the realization of a single person’s vision, but rather a collaborative effort, stemming from the collective roles of the cast, crew and all of those who have a hand in the film’s creation. However, as Jonathan points out, most people subscribe to the Auteur Theory without even realizing it. This point is illustrated through people describing a film as “Hichcockian,” or claiming that they prefer Spielberg-type films. This kind of talk reflects creative credit bestowed solely to the director.
Despite the circumstances—cast, crew, genre, plot—the director still leaves a recognizable imprint. Scorsese is visible in both Goodfellas and Hugo. Kubrick’s touch is noticeable in 2001 and Dr. Strangelove. Spielberg may use his usual crew of Williams and Kaminzki, or he may not, but you always know when it’s a Spielberg.
The directors described by the Auteur Theory share certain characteristics, some of these being vision for the present and future, leadership and confidence. A distinctive feature of the films from auteuristic directors is the appearance of stylistic tendencies. An example of this is French New Wave; it became a style of storytelling. Another characteristic is arising themes. This can be seen in Woody Allen’s cynicism or the social realism of the Dardenne brothers. Auteuristic directors also reflect growth and life changes in their film work. Spike Lee started out making films like Do the Right Thing and now makes films like When the Levees Broke; this illustrates his personal progression as a director and a person.
The Auteur Theory can apply to more than just film directors. For example, Facebook exudes Mark Zuckerberg’s personal style the same way that the creative vision of Steve Jobs is present in all that Apple does as a company. The style of Nintendo’s Shigeru Miyamoto can be seen in every Zelda and Super Mario Bros. game. These “auteurs” all leave their creative print in a very recognizable manner.
Jonathan subscribes to the theory of the “Group Auteur,” which is the idea that a group, company or entity can work together as one to achieve auteuristic results. While this may just seem like it describes performing as a good company should, it depends on how you view it. Certain companies like Pixar have created a company culture and standard that transcends their day-to-day operations and can be seen in every product it delivers. While employees come and go, the spirit and style of Pixar remains consistent. We can see this same group auteurism in Apple, which continues to function in the same fashion even after losing its influential CEO Steve Jobs last year.
For any auteur, every film or product continues the story. This progression tells the story of who the company is and how it evolves. As web developers, it is important to act as auteurs. The impression we make on the web scene should tell a story about our company. We should continue to strive to put out work that conveys a high standard of quality and a unique way of doing things. Every company and individual should brand their work in a recognizable and desirable way to build value, because if you stand for nothing, you’ll fall for anything.
Photo courtesy of Flickriver.
Code to Joy: Why HTML5 Makes Developers Happy
HTML5, the ambitious successor to HTML4.01/XHTML 1.0, was created with the intentions of improving the way the code is used by developers and understood by computers. New technology dawned new challenges for the code, and this latest version has been designed to deal with added applications while also attempting to further perfect the manner in which it handles previously existing issues.
This week, we talked to LB’s own front-end auteur Jonathan Pacheco to see what he found useful about the newest version of HTML versus its predecessors.
Semantic tags
While this feature isn’t necessarily anything new, HTML5 does differ in that it puts more focus than ever before on the use of semantic tags. While a <i> and <b> may still display text in italics and bold respectively, tags like <em> (short for emphasis) and <strong> continue to grow in popular preference due to their more descriptive characteristics of their function.
According to Jonathan, this evolution is due in part to a shift from an internal focus of understanding among developers to an external focus of computers’ ability to comprehend the coding embedded in web pages. HTML5 further encourages this transformation with the addition of semantic tags like <section>, <nav> and <article>.
Forms Made Easier
HTML5 has made the coding of forms much easier for developers like Jonathan by recognizing some of the useful functions of form data entry and making them standard. This includes features like disappearing/reappearing instructional placeholder text (i.e. “Enter you e-mail address here”) and the ability to recognize the format (e-mail address) and accept only the correct format (name@server.com). When using some devices (i.e. certain touchscreen smartphones and tablets), HTML5’s ability to convey this information also simplifies the data entry process by automatically providing the user with needed keys to complete the information, like the “@” or “.com” key for e-mail addresses or URLs.
Geolocation
Okay, we lied: the Geolocation Application Program Interface (API) isn’t part of HTML5, but we think it belongs in every HTML5 conversation. The standardization, emergence and increasing usage of the API, especially in the mobile world, perfectly coincides with HTML5’s push to empower developers to provide users with a more convenient, customized experience.
IP addresses have had the ability to determine location on a city level, but with the users’ permission, HTML5’s Geolocation feature has the ability to more accurately identify where users are and tailor their web experience accordingly. This includes informing users of nearby businesses that match their search and using general demographic and psychographic information to suggest services that are more likely to be of interest to users.
Canvas
HTML5’s canvas element simplifies the dynamic rendering of 2D graphics such as graphs, games and animation. The <canvas> tag and API simplifies the process of programming images that will change in response to the user’s commands or information.
For example, Jonathan says, a user could input information that is then dynamically rendered as a graph that displays the information given. If the user alters the information, the graph will change accordingly — thanks to HTML5’s canvas function — otherwise, each potential graph would have to be designed in advance in order to be available for display. The canvas element can be used as an alternative to Flash, which has proven to be difficult for some online devices to read.
Video
HTML5’s video capabilities make it even more of a match for Flash. With the ability to display in 3D and work with CSS3 and JavaScript to create customized controls and special transformations, HTML5 video is changing the way video is delivered online.
Overall, Jonathan had this to say about HTML5:
“The new technologies, techniques and APIs under the HTML5 banner aren’t just shiny new toys for geeks to tinker with. They’re helping evolve the web, making the creation process easier and more flexible for developers, allowing them to focus even more on crafting convenient and fun user experiences.”
It seems that Jonathan, like thousands of other developers, is excited about the latest developments made possible with HTML5. It just may be the best thing to happen to the web… that is until HTML6 is created.
Post brought to you by: Savannah Harper, LB Wordsmith and Jonathan Pacheco, LB Front-End Auteur
Saving the World From Bad Design:
Recently we came across a documentary being developed and showcased on www.kickstarter.com called “Design & Thinking” and it poses several questions to the Design Thinking approach and the incredible value that design plays in everything we do.
Shyam Patel, our LB Creatologist spoke last week at Ignite Dallas during the Big Design Conference on his approach to Saving the World from Bad Design and the value of design thinking and our current complacency with status quo.
“Design is not about just making things look better, it’s about making people’s lives better.”
We need to be conscience that every decision we make impacts the design of our own lives and the world around us.
In the movie trailer it spoke about the idea that “design is not a luxury, it’s a discipline”. We believe that to be true in all that we deliver. Maybe we could even elevate it to Design “doing” because we believe it is an absolute necessity in all our efforts at LB.
If we view the challenges of our society through the lenses of a design problem, the problems become infinitely more approachable and solvable. The industrial age taught us to be system thinkers, but the information age requires us to become design thinkers. We must stop being passive consumers and creators. We are not passive witnesses to these problems, we participate in them by the way we choose to design our lives and the work we do.
The industrial age encouraged us to gain a depth of knowledge in one area of expertise; the digital age requires that we supplement that depth of knowledge with a breadth of knowledge. Understanding all dimensions is critical and requires that we think through usability and aesthetics, form and function.
So what is design thinking? Well as I mentioned, design is about making people’s lives better – thinking and doing are about the process we use to ensure that we achieve that goal in whatever we are trying to create.
Let’s use form design as a great example. It’s amazing how applying design thinking to a form can change the world. Think about default options of a form. This country suffers from an abysmal savings rate due to over consumption. By changing the default option on 401(k) plans to be opt out saving rates have been shown to increase to 11% compared to negative savings rates nationally.
That’s design thinking and design doing at its best. We must pledge to be design doers. Saving the World from Bad Design means no more status quo, it means challenging ourselves to ask questions, absorb information and ultimately deliver better end results.
Our LB mantra…
We believe that design is a craft at the intersection of art and science, form and function. It is about more than being creative; inspiration and innovation are its fundamental principles. Design is about having the courage and the audacity to pursue our vision through our work to make the world what it can and should be and not settle for what it is now.
To see Shyam’s presentation for Ignite Dallas, check it out here: http://slidesha.re/oMul4V
Photo/illustration courtesy of: Emerson College blog post b
From the LB Lab: Magento and SVN With Dynamic Base URL
Magento has solved so many problems in the ecommerce world and it is great software out-of-the-box. However, it presents some interesting challenges when trying to make it work in a team environment. In fact, because of things like the “base url” stored in the database and the “var” directory that holds the cache and other meta data, using something like SVN requires some changes “under the hood”. I faced this issue, did some research and found an excellent post by Jools Wills that helped a bit - found here. His solution is straight-forward and effective, except that it’s two years old at the time of writing. Magento has changed a bit, as well as the methods he overrides. Here is my updated solution based on his initial outline.
The first problem to overcome is that the “base url” is stored in the database. For most team development environments the database is shared and the files are pulled down using SVN or some other version control software and the developers each run their own instance locally. Since changing the base url in the database would only enable one instance of Magento to work at a time, we need to dive under the hood and make some changes. We are going to use a server variable provided to us by PHP to establish the base url instead of pulling it from the database.
Making the Base URL Dynamic
First we need our own custom module. There are many good resources available that explain how to do this. But for now, we won’t cover that in detail. We use “LB” as our namespace and “Core” as our module. You can replace those with whatever you choose, as long as you are consistent. Any time you see “LB” put your namespace in. You should use “Core” for your module since we are overriding one portion of the Magento “Core” module. The first file registers our namespace and module with Magento.
Here is the first file: app/etc/modules/LB_All.xml
<?xml version="1.0"?>
<config>
<modules>
<LB_Core>
<active>true</active>
<codePool>local</codePool>
</LB_Core>
</modules>
</config>
Now that we’ve registered our module for use in Magento we need to override the important method, that being “Mage_Core_Model_Store->getBaseUrl()”. The following XML file does just that. Note that you’ll have to create some directories here. Make sure that if you are using something besides “LB” you create a directory with that name instead of “LB”.
File: app/code/local/LB/Core/etc/config.xml
<?xml version="1.0"?>
<config>
<global>
<models>
<core>
<rewrite>
<store>LB_Core_Model_Store</store>
</rewrite>
</core>
</models>
</global>
</config>
That takes care of configuration. We are now ready to dive into some PHP code. We have already told Magento to override the “Mage_Core_Model_Store” class in the configuration, now we just need to add our class.
File: app/code/local/LB/Core/Model/Store.php
<?php
/**
* We are overriding functionality in Mage_Core_Model_Store
*
* @author Life Blue
*/
class LB_Core_Model_Store extends Mage_Core_Model_Store {
const USE_DEV_URL = true;
protected function getDevelopmentUrl($secure) {
$secure = is_null($secure) ? $this->isCurrentlySecure() : (bool) $secure;
if ($secure) {
$url = "http://" . $_SERVER['HTTP_HOST'] . "/";
} else {
$url = "http://" . $_SERVER['HTTP_HOST'] . "/";
}
return $url;
}
public function getBaseUrl($type=self::URL_TYPE_LINK, $secure=null) {
$store_code = $this->getCode();
if (self::USE_DEV_URL != true) {
$url = parent::getBaseUrl($type, $secure);
}
$cacheKey = $type . '/' . (is_null($secure) ? 'null' : ($secure ? 'true' : 'false'));
if (!isset($this->_baseUrlCache[$cacheKey])) {
switch ($type) {
case self::URL_TYPE_WEB:
$secure = is_null($secure) ? $this->isCurrentlySecure() : (bool) $secure;
$url = $this->getDevelopmentUrl($secure);
break;
case self::URL_TYPE_LINK:
$secure = (bool) $secure;
$url = $this->getDevelopmentUrl($secure);
$url = $this->_updatePathUseRewrites($url);
$url = $this->_updatePathUseStoreView($url);
break;
case self::URL_TYPE_DIRECT_LINK:
$secure = (bool) $secure;
$url = $this->getDevelopmentUrl($secure);
$url = $this->_updatePathUseRewrites($url);
break;
case self::URL_TYPE_SKIN:
case self::URL_TYPE_JS:
$secure = is_null($secure) ? $this->isCurrentlySecure() : (bool) $secure;
$url = $this->getDevelopmentUrl($secure) . $type . "/";
break;
case self::URL_TYPE_MEDIA:
$secure = is_null($secure) ? $this->isCurrentlySecure() : (bool) $secure;
$secureStringFlag = $secure ? 'secure' : 'unsecure';
$url = $this->getDevelopmentUrl($secure) . $type . "/";
if (!$this->getConfig(self::XML_PATH_USE_REWRITES)
&& Mage::helper('core/file_storage_database')->checkDbUsage()) {
$url = $this->getDevelopmentUrl($secure);
$url = str_replace($urlStart, $urlStart . self::MEDIA_REWRITE_SCRIPT, $url);
}
break;
default:
throw Mage::exception('Mage_Core', Mage::helper('core')->__('Invalid base url type'));
}
$this->_baseUrlCache[$cacheKey] = rtrim($url, '/') . '/';
}
return $this->_baseUrlCache[$cacheKey];
}
}
If you look at the “getBaseUrl” method you may notice that it starts out with an “if” statement that indicates that we need to use dynamic base urls. For a production environment all you need to do is set “self::USE_DEV_URL” constant to “false” and the original “getBaseUrl” method is called.
That takes care of the “base url” portion of the problem. Now we need to address the “var” directory.
Cache and the “var” DIrectory
We will do this by allowing it to be checked out initially, but then ignoring it after that. We are only going to cover how to do this with Tortoise SVN. You’ll have to research other versioning systems and please post comments for other solutions you find!
First you need to push your whole Magento implementation into your repository. Don’t exclude the “var” directory. Other people will need to pull that down for Magento to work properly. If you want, you can clear out the sub-directories within “var” to make things a bit more clean. If you choose to do so, make sure you know what you are doing. You can cause things to stop working. You have been warned.
Once you have done your initial push to SVN it’s time to set the “svn:ignore” property on the “var” directory. You can do this the hard way and set it using the “properties” utility Tortoise provides, or you can take one or two extra steps that simplifies things as well as making them a bit more but not completely “fool proof”.
- Export the “var” directory to itself. In Tortoise, right click the “var” folder and select “TortoiseSVN > Export .”.
- You will be presented a dialog asking you where you want to export to.
- Navigate right back to where the “var” directory lives, such as “C:\xampp\htdocs\magento\var” and export.
- When it asks you if you want to unversion these files select “Yes”.
- Now right click the “var” again and select “TortoiseSVN > Export > Add to ignore list > var”.
Now the “var” directory will not commit for two reasons. First, it is not versioned and will need to be added back in to run a commit. Second, “var” is set to be ignored when a commit is run. That means it shouldn’t ask you if you want to add them.
As I said earlier, this is relatively fool proof. However, you still have to pay attention to make sure the “var” directory does not get included in a commit. Software such as Netbeans may not respect the “svn:ignore” property like you expect. However, if you are careful you can just run an update on the whole instance of Magento without fear of getting someone elses “var” contents and goofing up your working copy.
I hope that helps you with your Magento development. If you have any questions or have some additional suggestions leave some comments
PHP And Caching
The last few weeks I’ve been poking around the internet looking for some good information on creating a caching system using PHP. I found that this little niche of PHP knowledge is either still in the dark ages or isn’t something people have felt the need to blog about. I’m guessing it’s a bit of both. Caching isn’t really that sexy as far as programming goes. It’s fun to say “our software does extensive performance caching” in tech specs but the actual creation of that system often puts developers off as it requires a bit of forethought and planning to make a good one. I recently undertook this task and thought I might share my experience.
First, I really wanted to have a system that didn’t rely on one storage medium, didn’t have to use one monolithic caching policy, and could cache just about anything using a common interface. That way I could cache a whole page, an html fragment, a serialized object or a database result. I could also put it where I wanted, be that the file system, the database, or to a web service. This flexibility isn’t truly necessary for any particular project, but becomes really nice when you have to change up what you cache frequently. Let’s take a quick look at what I came up with.
Creating Interfaces
First I broke the system up into three components.
- Cache Entity - This is the actual item that is slated to be cached.
- Cache Policy - This helps write a class that in turn defines rules for when a cache entity is valid and when it’s ready to be discarded.
- Cacheable - This interface is applied to an item that can be cached. It may or may not also be a cache entity. The interface is designed to turn already implemented caching defined further up the inheritance chain using the
instanceofkeyword. Technically isn’t necessary, but I liked the idea since it allows me to be very targeted in what I do and don’t cache.
Implementation
After the interfaces are set up, we just have to implement our big ideas. Here’s a fun example of how that might go.
The Cache Entity
This class, derived from an interface, helps us define two things. First it defines what is being cached. Second, it defines where that item is being cached. The later is hidden and should be opaque to the client programmer using this class. The should never have to worry about if it’s cached in the file system or in the database.
class StudentEntity implements CacheEntityInterface
{
public function SetCachePolicy($instanceOfACachePolicy)
{
// Set the cache policy that will be used to validate this entity
}
public function CheckCache()
{
// Use the cache policy we set above to check to see if this
// cache object is still good.
}
public function RenewCache()
{
// Renew the cache as if it were brand new.
}
public function InvalidateCache()
{
// Throw the cache away.
}
public function LoadCache($somethingThatTellsUsWhereToFindTheCacheEntity)
{
// Code that fetches us the cache Entity
}
public function GetCache()
{
// return the object that we've cached.
}
public function SetCache($objectToBeCached)
{
// Set up the object to be cached.
}
}
The Cache Policy
This class defines the rules for when a cache entity is ready to be used or ready to be thrown out in favor of re-creating the item. For the most part I didn’t see the need to create an xml based schema to hold these rules as it would mean overhead. In something like Java or C# that might make sense. Here just a simple PHP class is the simplest and most efficient method.
class StudentCachePolicy implements CachePolicyInterface
{
public function ValidateCache($cacheEnity)
{
// either call protected/private methods or
// just check to see if the cached object is
// usable or it it's to old, corrupted, etc.
}
}
The Actual Cachable Objects
The cacheable interface really doesn’t have to have any associated methods. I put some in there because I wanted to constrain how something was cached a bit further. You really don’t need to. Let’s look at how the interface might be used.
class CheerLeader extends Student implements Cacheable
{
// Because if you've seen one you've seen 'em all.
}
class PreppyKid extends Student implements Cacheable
{
// Because you can't be a prep if you are different.
}
class Nerd extends Student
{
// He may be a student, but he's one of a kind, don't cache this one.
}
class Student
{
function __construct($student, $data)
{
if($this instanceof Cachable)
{
// define this object based on the cache
}
}
}
Since (in my humble opinion) all cheerleaders and preps are the same, we will cache them and not go through the trouble of creating a new one. We’ll just used the cached version since they have the "Cachable" interface. If it does not have that interface, we don’t cache it. This allows us to cache things that will almost never change and not waste any time when we already know we’ll need to create an object from scratch.
Conlusion
While this is pretty skeletal, it should provide a nice starting point to building a system that can cache most anything and store it most anywhere. With this kind of granularity the programmer can be very picky about what we are caching an what we are not. The end result is a caching system that can serve all the systems within your application rather than just page renders or database results.
Happy caching!
Open Your Source
Pros and cons of making your application base publicly accessible
Introduction
Having spent a significant amount of time working with third-party APIs, application libraries and lifeBLUE’s own internal PHP framework, I noticed several trends in terms of usability and improvability. Obviously adherence to programming standards, organization and quality of code are huge factors that come into play for these categories, but I wanted to focus on the idea of open-sourcing application frameworks and how it can make or break your software. In this entry I’ll discuss the pros and cons of opening your source up to the community, and how you can manipulate community questions and solutions to improve upon your application model.
The Future Of Frameworks
Having an open-source solution is becoming a huge selling point for several applications, frameworks, and languages. Even Microsoft has considered open-sourcing C#, one of the strongest and most desirable web development languages available. Open-source projects arise from community demand for modular solutions, which are easily modifiable to one’s particular needs. These open-source frameworks are then subject to extension which means they have to be developer friendly, or at least have a considerable amount of documentation and community backing for it to be successful. This requires additional documentation, coding consideration, and an active support presence. Seems like more work right? Sure there are sacrifices and drawbacks to having a successful open-source project, but you have to realize you are trying to appeal to a very specific target audience. The audience: web developers.
Popular Demand
What is the most popular web development language around? Most would argue PHP. Is that because it has a widely accepted, well tested, extensive framework behind it? No, actually it’s lacking in that department. Is it because it holds up to programming standards? No. If anything, it goes against a lot of them! So why then is it so popular?
First of all it’s free. Second it’s open-source. Being free makes sense, but how does being open-source contribute to its popularity? It’s actually very simple when you look at it from the perspective of computer scientists. Extensibility and individuality! Give me another language library that provides just enough to do what I need and let me write the rest myself the way I want to write it.
The amount of time and effort it takes to understand PHP as a whole vs. C#.NET or Java is significantly less daunting, and most web applications require a mere fraction of the code present in an out-of-the-box .NET or Java install. The only drawback to this kind of thinking is that it puts a lot of responsibility on the consumer… or is this really a blessing in disguise?
E-Socialism
How you handle feedback is critical. Disregarding this free error and usability reporting is not only negligent on your part, but is also a slap in the face of your consumers. If you take the time and effort to make a well developed framework, make it public to the community, and take into consideration the feedback from that community, they will praise you and your product. Developers want to use your application because they know it works well and that they can rely on you and the rest of the community to continue improving upon the framework as well as answer their development questions. If anything, you will get free user testing from REAL end users with REAL business requirements. Obviously you can’t implement every single feature or address every single request, but the idea is to pick and choose which items are deemed necessary by the community or coincide with your own business plans.
Popular, But Is It Profitable?
Too many software development companies fall into the trap of thinking they can only make money by providing actual software solutions, yet there are free open-source projects that are obviously receiving funding from somewhere. Where does this money come from? Support plans, seminars, training sessions, donations, extension packages, consultant and development services, etc.
Stop thinking about how to sustain your business and start thinking as a community leader. You can focus on obtaining new users and businesses, retain fans and followers, and can more appropriately budget your business based on reliable, recurring income – not just the possibility of making a big sell.
Wrapping Up
Lastly, I would like to give kudos to my favorite open-source frameworks that have done a great job taking community feedback and delivering real, intelligent framework updates. If you are looking for good, potentially free software for your web project, I recommend you look up and consider some of the following open-source frameworks. No, they didn’t pay me to pitch their product I just have a lot of respect for their work ethic and business direction, and therefore support their product. In addition I will give a rating on the learning curve necessary to use the product, 1 being simple and 10 being difficult.
Note: Before you decide to turn to these as your web solution let me assure you that in no way will these frameworks be a one-stop solution for most web projects. You will have to spend a significant amount of time just to learn the frameworks, let alone construct and develop your own designs, functionality, and interactive components. This is where you should look for an interactive agency (such as LifeBLUE Media), a web development group, or even a freelancer to do development work. The good thing is that if you can find a team or individual that understands these open-source frameworks you can save yourself a considerable amount of time, money, and effort while coming up with a better, more stable result.
Umbraco, “the friendly cms”
Learning Curve: 5 out of 10
Umbraco is one of the leading ASP.NET content management systems out there. Having used it on numerous projects and having modified their source code myself, I can safely say that they have constructed a strong and versatile system that any competent developer can utilize to achieve a wide range of content delivery.
You still need to know the basics of web development including HTML, CSS and JavaScript. And if you are looking for any advanced functionality you will most likely need to know ASP.NET and take a little more time learning Umbraco’s class library, which is well organized and takes what I would consider to be an appropriate amount of time to understand and utilize properly. They provide a large amount of online support, have lengthy yet pertinent documentation, and have a great forum for feedback, Q/A, and bug reporting. Not to mention…IT’S FREE!
For more information visit - http://umbraco.org
jQuery, “write less, do more”
Learning Curve: 3 out of 10
If you have been in web development for any extended period of time, you’ve probably run across the jQuery framework. jQuery and other similar frameworks are quickly redefining interactive web components in a staggering manner. Unfortunately for proponents of Flash, the power and flexibility of these client-side scripting libraries is leveling the playing field for web animation. In addition jQuery has strong yet simple AJAX functionality which is becoming a standard web technology for web applications. The open-source nature of jQuery has allowed for the development of numerous jQuery extensions and plugins, some of which we have worked with and developed ourselves. jQuery is also free and is a powerful resource for developers no matter what the project requires. You will still need to know basic JavaScript, and finding the exact behavior you desire may take a little bit of digging online, but every adopted function and/or plugin is well documented on jQuery’s support website. If you can read it, you can implement it.
For more information visit – http://jquery.com
Honorable Mention:
Magento - Learning Curve: 7 out of 10
Widely accepted PHP based ecommerce solution
For more information visit - http://www.magentocommerce.com/
Logic Busters - Part 1: Singletons
Identifying and eliminating double instantiation of objects and single-synchronous-request “caching”
“Logic Busters” is a continuation of the “Schema Busters” series with an emphasis on business-logic practices that you can implement when engineering your web-applications. The concepts discussed in this series will differ from the previous in that they are geared towards programming practices and tips as opposed to database schema and query design. In this first section we will discuss the concept of singletons, how to implement singletons, and efficiency gains from the utilization of singletons. Since singletons deal heavily with object management and objects have a tendency to be reflective of database entities I hope this subject will serve as a proper transition from our database studies into the realm of application logic.
What is a Singleton?
The singleton is a mathematical concept that simply states any instance of an object must be equivalent to itself and is universally unique from all other objects. If there were another object with the exact same properties it would be one and the same as the original. In programming it is quite possible and easy to violate the Singleton concept. Imagine instantiating two copies of an object and performing separate and distinct operations on them effectively make them unequal. This in turn destroys any possibility of maintaining object singularity.
Why use the Singleton pattern?
Before continuing let’s analyze the benefits and costs of such behaviors. Obviously being able to manipulate two copies of the same object independently provides great flexibility, but at what cost? An immediate concern rises in the situation of multithreaded or asynchronous environments (multitasking in laymen’s terms), where data integrity and symmetry can prove vital. This issue is best illustrated by looking at a concept called conflicting transactions which is more commonly associated with database transactions. Imagine that we have the following database table:
tblUser
userId login password email active
…and the following two transactions where the value of “@parameter-name-here” is passed at transaction call:
Name:
Trans_UpdateUserId
Description:
Updates the user id
Query:
UPDATE tblUser SET userId = @userId WHERE userLogin = @userLogin
Name:
Trans_UpdateUserEmail
Description:
Updates the user email
Query:UPDATE tblUser SET email = @email WHERE userId = @userId
If we are to run these two transactions independent of each other on a user with the below described data, we now have three scenarios:
User:
1. userId = 1
2. login = ‘JGFree’
3. password = ‘secret’
4. email = ‘jgfree@lifeblue.com’
Transaction Scenario 1:
1. Trans_UpdateUserId is run with @login = ‘JGFree’ and @userId = 2
2. Trans_UpdateUserId finishes
3. Trans_UpdateUserEmail is run with @userId = 1 and @email = ‘new@email.com’
4. Trans_UpdateUserEmail finishes
5. Final state of user:
userId = 2, login = ‘JGFree’, password = ‘secret’, email = ‘jgfree@lifeblue.com’
Transaction Scenario 2:
1. Trans_UpdateUserEmail is run with @userId = 1 and @email = ‘new@email.com’
2. Trans_UpdateUserEmail finishes
3. Trans_UpdateUserId is run with @login = ‘JGFree’ and @userId = 2
4. Trans_UpdateUserId finishes
5. Final state of user:
userId = 2, login = ‘JGFree’, password = ‘secret’, email = ‘new@email.com’
Transaction Scenario 3:
1. Trans_UpdateUserId is run with @login = ‘JGFree’ and @userId = 2
2. Trans_UpdateUserEmail is run with @userId = 1 and @email = ‘new@email.com’
3. Inconsistent behavior from here on out since both transactions will try to access same record at the same time.
4. Note that this inconsistency can also be caused by switching 1 and 2 of this scenario.
For the sake of our discussion we will disregard Transaction Scenario 3 since this kind of conflict is more appropriately addressed by Database Management Systems and Memory Access Systems and how they handle this kind of simultaneous access conflict, a concept that is not pertinent for us at this moment. The reason I use these transactions is to show that two copies of the same object, like the above user with the above described properties, subjected to two different transaction scenarios can result in different object states.
Now we should stop and consider that this behavior is either desirable or undesirable depending on your project’s technical specifications. If it happens to be desirable then we can disregard this entire study and get back to work (you time-thieving, blog-trolling slacker). Otherwise we can begin the implementation of Singletons to make sure that object state is maintained across multiple transactions.
Implementing Singleton objects and how they work
Implementing a Singleton requires little additional coding, but a strong consideration for consistency. The basic concept is to statically store an instance of whatever object we are creating a singleton out of, and upon redundant load calls we simply reference the static singleton object. Most object-oriented classes have a constructor or instantiate method that loads all of the properties of an object based on its identifier. When initially called, we should check if the identifier matches that of our singleton object. If so we return the singleton object. Otherwise we continue loading the new instance and replace our singleton object with the resultant object. In a similar manner, every time we make a change to our object we must also update the singleton.
Immediately we can see how this kind of structure can reduce our database calls significantly. Imagine that we load the same instance of an object three times throughout the span of a request. Utilizing the singleton concept we now reduce our database use by 66%. We can expand upon this idea by allowing for Singleton Dictionaries which is simply a static collection of objects mapped by their identifier. If we are loading all users three times throughout the span of a request, we are now producing significant traffic (dependent on your user pool obviously). Since it is semi-difficult to include code in this blog and the code I would provide is available elsewhere, I will simply refer those interested to sites already containing examples of singleton use:
-http://www.developertutorials.com/tutorials/php/php-singleton-design-pattern-050729-1050/
-http://www.talkphp.com/advanced-php-programming/1304-how-use-singleton-design-pattern.html
Now hopefully your program does not require you to load every single user three distinct times in a single request. Singletons are extremely situational and are not your primary means of reducing resource use. An obvious place to implement a singleton would be for managing the object currently logged in since it often gets referenced multiple times in a page load. Look for these kinds of situations to implement this data structure.
Conclusion
Looking back at our example where we performed asynchronous transactions on a non-singleton object yielding different possible results, we can now see how a singleton would enforce the legitimacy of both transactions. Each transaction would update the singleton which would then be the result of both transactions as opposed to any kind of deviation produced by the order of transaction operation. Transaction 1 will now produce the same results as Transaction 2 since the userId is consistent for both transactions, Trans_UpdateUserEmail and Trans_UpdateUserId.
Singletons are a great data structure to consider when tweaking your application to maximize performance. They are not the answer to all of your resource management needs, but they serve their purpose beautifully. If you enjoyed learning about this data structure and how it can be applied, I encourage you to seek out other data structures as they have the potential to improve your site/application performance and reduce the complexity of your code. I recommend beginning with the “Current User” example I provided above, and then reevaluate your program to see where this kind of technology makes sense.
PHP Factory Design Pattern Part 1
For my next several blogs I’m going to be discussing a powerful PHP design pattern, the factory. Since PHP applications and the data structures they interface with are getting larger and more complex there is a need to streamline and simplify how these data structures are loaded into useful objects.
For example, let’s take robust CMS. A simple CMS has only one content type: a page. However, for more complex CMS systems you have multiple content types such as events, publications, and even products. Each one of these content types needs to have its own properties and methods that are unique to that content type. We end up with a problem. How do we deal with the unique needs for each type of content and maintain an efficient application?
It makes no sense whatsoever to include all of the properties and methods for every content type into a single class definition and database table. The class would be a behemoth. Once the object was loaded it would be a resource hog, eating up memory and processor power. On a small site with little traffic this might be ok, but any high volume CMS would grind to a halt under these conditions.
On the flip side, doing a new unique class for each content type is not much better. To request a piece of content then render it properly to the browser you would need to search across multiple classes and database tables. Not only that, because there are multiple tables, there could easily be URL and naming conflicts. Also, great care would have to be taken to ensure that all of these objects followed a common interface. If not, loading appropriate content could become a “switch case” and “if else” nightmare. Maintenance on that kind of system gives me the shivers just thinking about it.
Enter the factory design pattern. This design pattern lays out a few nice rules that simplify situations just like our example. First it would allow for a unified method for loading all content types, from one place. Second it would require consistency within all the classes. Everything would have to work the same way on a basic level, and the unique functionality would be in addition to that. There would be one central place where the core data was loaded, and then any extra information would be held in it’s unique storage medium, such as a database table.
First let’s look at what a factory is:
- A factory is a class that is designed to load various types of objects that all share a common interface.
- A factory class does nothing but load objects.
- A factory intelligently decides what object should be loaded based on the parameters it is given.
- Most often the objects a factory loads have a shared purpose.
Let’s look at what defines the factory design pattern:
- Classes the factory loads are structured in a similar way so that they can be loaded using the same basic method call.
- Classes the factory loads follow a unified structure, most often defined by a parent class or an interface.
- Classes the factory loads do not need anything from the factory once they are loaded. The factory’s job is done.
As you can see, the factory pattern provides a means to load similar objects from one place. It is an extremely useful pattern within PHP web applications. In my next post I’ll provide some UML and coding examples to flesh out this useful design pattern.


RSS Feed
Atom Feed

