Creative Meat Blog
Development

Oneupweb : OOP Naming Conventions

Posted by Robert in Development, Opinions, Tutorials on January 18, 2012 - 6:10 pm

While working with different Object Oriented Programming (OOP) languages and frameworks, I’ve seen quite a few approaches on how to format various items. The line between personal preference and “best practices” has become blurry when dealing with naming conventions.

I have no idea what I'm doing: dog on a computer.Some decent advice on that subject is to adapt to the style of the current environment. However, even within languages it’s not uncommon to find inconsistencies. For example, take a look at the concatenated acronyms in XMLHttpRequest for JavaScript. XML is all uppercase, while Http is mixed upper and lowercase. There is no clear text treatment, making it unintuitive and more difficult to remember.

For this reason, it is a good idea to treat acronyms as words. While not immediately clear, it eliminates the guess work when attempting to recall a particular class, method or attribute; especially since acronyms tend to evolve. For example, the phrase “Away From Keyboard” eventually became “AFK” and is commonly typed as “afk”. By treating it as a word, you won’t have to guess which casing to use, just follow your chosen convention.

So, what if you have the chance to write your own library from the ground up? Perhaps something portable that shouldn’t be married to one particular language or uses many languages; what naming practices should you follow then? Of the examples I’ve seen and used in the past, here is what I personally prefer on a basic level.

class ClassName
{
  public static const MAX_USERS = 15;

  public var variable_name = "foo";

  private var _variable_name = "bar";

  public function methodName()
  {
    // do something
  }

  private function _methodName()
  {
    // do something
  }
}

ClassName

Classes use upper camel case, meaning each concatenated word begins with a capital letter followed by lowercase letters.

class ClassName
{
  // stuff
}

methodName

Methods use lower camel case, meaning the first word is all lowercase, while each additional word begins with a capital letter followed by lowercase.

public function methodName()
{
  // do something
}

variable_name

Variables use lowercase words, separated with underscores. They are dynamic objects that are usually defined on a per instance basis.

public var variable_name = "hello world!";

CONSTANT_NAME

Constants use uppercase words, separated with underscores. They are unchanging values and are typically also static (accessible directly from a class).

public static const CONSTANT_NAME = "foobar";

// accessible through the containing class without a need to instantiate.

var variable_name = ClassName.CONSTANT_NAME;

_private_variable and _privateMethod

Private variables and methods are prefixed with “_” (underscore). They are accessible only from within the object instance in which they are used. By placing an underscore before the name, the scope is instantly recognizable, keeping them separate from public variables and methods.

private var _variable_name= "foo";

private function _methodName()
{
  return "bar";
}

There are other considerations that play even deeper into personal preference, such as curly-bracket “{}” placement for functions vs loops vs if-statements. Spacing for within and around parentheses “()” is equally preferential. How you format your code is ultimately up to you and how you find it the most readable.

Again, what I mentioned above is very generalized and won’t necessarily stand well in some languages. Adapt to your environment and please, do leave comments below. I enjoy reading other programmers thoughts and opinions.

GD Star Rating
loading...
Development

Oneupweb : Cross Browser Event Binding Without jQuery

Posted by Brian in Development, Tutorials on January 10, 2012 - 6:05 pm

This past weekend I was having a conversation on JavaScript with a developer friend of mine and we got on the topic of how jQuery has drastically altered the JavaScript landscape. Don’t get me wrong, jQuery is an excellent library. It makes cross browser events and effects a snap. The problem is it has become universally depended on for even trivial tasks. There seems to be a tendency to learn jQuery and not JavaScript.

People asking JavaScript questions on a site like Stack Overflow are inundated with responses to the effect of “why not just use jQuery.” Well yes… you could accomplish it that way, but it doesn’t help the asker of the question to understand anything new about JavaScript.

an honest question

An honest JavaScript question

A not so helpful response

A not so helpful response

Do It The Right Dom Way

If all you need to accomplish is a simple hide/show function at the click of a button, then why include the whole jQuery library? Do you really need all that code mucking up your window for such a simple task? Lets go over the basics of creating a nice lean cross browser event and css tool in JavaScript.

Binding Events

The trick to binding events that work in multiple browsers is basically understanding the Internet Explorer method and the standard method defined by the W3C.

element.addEventListener

This is the standard way to setup events in a document. A great introduction to this method can be found on the Mozilla Developer Network.

The syntax is as follows:
target.addEventListener(type, listener, useCapture /* Optional */);

document.getElementById('mybutton').addEventListener('click',function(e){
    //"this" refers to the event target ie the button that was clicked
    alert(this.value);
},false);

The function you pass in to addEventListener will receive the event object as its first argument. Within the function the this keyword refers to the element that was clicked. The false passed at the end keeps the element’s parents from getting to the event first (this is ok for most basic uses);

element.attachEvent

Internet Explorer is not historically known for working with standards. Internet Explorer, before version 9 (though 9 still supports it), relied on element.attachEvent for event binding.
The syntax for this is:
target.attachEvent(ontype, listener);
Just replace type with the event you would normally use in element.addEventListener. So click becomes onclick, change becomes onchange, etc…

document.getElementById('mybutton').attachEvent('onclick',function(){
    //attachEvent relies on a global event object to get the target
    var elem = event.srcElement;
    alert(elem.value);
},false);

A Cross Browser Function

You can’t just choose one or the other. Ideally you will have one way to bind an event and you should be confident that whether your document is being viewed in IE7+, Firefox, Chrome or whatever – the events should all work the same.

Our function needs to test whether or not the browser supports element.addEventListener or element.attachEvent and react appropriately.

var bindEvent = function(elem ,evt,cb) {
    //see if the addEventListener function exists on the element
	if ( elem.addEventListener ) {
		elem.addEventListener(evt,cb,false);
    //if addEventListener is not present, see if this is an IE browser
	} else if ( elem.attachEvent ) {
        //prefix the event type with "on"
		elem.attachEvent('on' + evt, function(){
            /* use call to simulate addEventListener
             * This will make sure the callback gets the element for "this"
             * and will ensure the function's first argument is the event object
             */
             cb.call(event.srcElement,event);
		});
	}
};

Not so bad right? You now have a cross browser way to bind events without all the stuff you don’t need.

Using the Function

This function is really easy to use.

var button = document.getElementById('button');
bindEvent(button,'click',function(e){
    alert(this.value);
});

Test this in IE7+ and your favorite modern browser and see it in action.

Making Your Own Event Tool

One of jQuery’s most attractive features is the syntax. We can mimic this syntax in a simple way and still trim a ton of fat. We will make a simple tool that allows us to cash in on this syntax.

Introducing Boss.js:The Lightweight JavaScript Library

Ok…not really. This is overly simplified, but it demonstrates how easily this can be done. Create a file called boss.js. We are going to use the module pattern to create our library. Explaining all this is a bit beyond the scope of this article, but I will try to comment things for the adventurous. Put the following code in this file:

(function(){
    //the function we just made
	var bindEvent = function(elem,event,cb) {
		if ( elem.addEventListener ) {
			elem.addEventListener(event,cb,false);
		} else if ( elem.attachEvent ) {
			elem.attachEvent('on' + event, function(){
				cb.call(event.srcElement,event);
			});
		}
	},

    //we will use the popular dollar symbol
	$ = window.$ = function(id) {
        //the $ returns a new Boss object
		return new Boss(id);
	},

    //the Boss object constructor
	Boss = window.Boss =  function(id) {
        /* rather than have full selector support, Boss only supports id's
         * boss stores a reference to the elment for later use
         * we explicitly check to see if the id is the window
         * for cases where we want to bind events to the window
         * (something like a load event)
         */
         if ( id === window ) {
             this.elem = window;
         } else {
             this.elem = document.getElementById(id);
         }
    };

    //set up the methods that belong to a Boss object
	Boss.prototype = {
        //this is just a wrapper over our bindEvent function
		bind:function(etype,cb) {
            //use the elem reference
			bindEvent(this.elem,etype,cb);
            //return the Boss object for chaining
			return this;
		},
        //a simple getter setter for style values
		css:function(property,value) {
            //if the property and value are both passed, we are setting the css
			if ( property && value ){
				this.elem.style[property] = value;
            //otherwise we are returning it
			} else if ( property ) {
				return this.elem.style[property];
			}
		}
	};

})();

Save it and Boss.js is born.

Using Boss.js In a Web Page

Setup a simple web page with the following:

<!doctype html>
<html lang="en">
<head>
	<title>JavaScript events</title>
	<script src="./boss.js"></script>
</head>
<body>
	<form action="" method="get">
		<p>
			<input type="button" name="button" value="Toggle Visible" id="button" />
		</p>
		<div id="toggleMe">
			Now you see me!!
		</p>
	</form>
</body>
</html>

Then in the header we will attach to the load event of the window to make sure our document is read. Place the following code in the head section of your document, right below the script element that includes Boss.js:

<script>
$(window).bind('load',function(){
	var toggleMe = $('toggleMe');
	$('button').bind('click',function(e){
		var display = toggleMe.css('display');
		display = (display === "none") ? "block" : "none";
		toggleMe.css('display',display);
	});
});
</script>

The bindEvent function is a simple way to handle events without the whole jQuery library. It’s proof that you can use native JavaScript to accomplish a lot.

GD Star Rating
loading...
Development

Oneupweb : ROSI TRAX™ — Track Social ROI With Short URLs

Posted by Brian in Development, Tools on December 9, 2011 - 2:11 pm


Hot on the trails of my brilliant colleague Robert Hall’s article on ROSI trax™ and social buttons, I decided it would be a good idea to talk about the other side of ROSI.

A typical scenario

We will once again rely on the fictitious dairy treat company known as Mootropolis to illustrate how ROSI does business.

Mootropolis’ head of marketing Nancy is a good little social butterfly, and she keeps the buzz for Mootropolis alive and well on Twitter. Nancy wants to get the word about their new flavor “Triple Chocolate Gnarly Cake Nugget Surprise,” and so she does what comes natural. She heads to Twitter and tells people where they can go find out more about the product:

This is fine and dandy. Nancy managed to get a link on their Twitter stream, so all of their followers can easily click it and find out more about tasty gnarly cake nugget ice cream. Perfect. Right?

NOPE!

Mootropolis is marketing to these people right? Wouldn’t it be nice to see who actually bought some of Mootropolis’ delicious new flavor as a result of that tweet? It can be done!

Enter the ROSI trax URL Shortener

Instead of posting that “http://www.mootropolis.com” link, why not shorten that bad boy down in the ROSI trax URL shortener and gain these spicy benefits:

Track total visits
Track unique visits
Track conversions and their value

Nancy puts her mootropolis URL into ROSI trax, and out comes a newer, shinier short URL; packed with all of ROSI’s tracking goodness.

Nancy can now see how her tweets translate to dollars and cents:

Nancy can now see all the visits, unique visits, and conversions that result from people who click on the links she tweets.

Think of the possibilities!

Now that Nancy has seen the light, and she is tracking conversions from Twitter, she starts to think of all the other places she can put a ROSI trax short URL:

Mootropolis’ Facebook Wall
Email campaigns
Tumblr
YouTube
Blogs
Just about anywhere you can share a link!

Cash in like Nancy

Start tracking your social investment like Nancy. ROSI trax™ is easy to use and available to Oneupweb clients. Contact a member of our sales team to discuss the possibilities today! Request a Proposal

GD Star Rating
loading...
Development

Oneupweb : Magento Module Development Part 2: Adding Scripts and Styles

Posted by Brian in Development, Tutorials on November 17, 2011 - 2:49 pm

For new comers or novice Magento module developers, you may want to head over to part 1 of the Magento Module Development series

Creating a lightbox plugin for Magento product pages

Armed with the knowledge to create a Magento module, it’s now time to do something with our new found prowess! We are going to start by augmenting existing functionality in Magento. I think the pop ups for product images leave a lot to be desired. I think it’s time we spice things up a bit and add a light box feature to those picture thumbnails.

Default pop-up for a product. Bleh!

We want something a little fancier. We are going to pick up where we left off in part 1 and use our module knowledge to implement jQuery colorbox on our product pages:

Colorbox product - very much sexy!

Setup config.xml

Location: /app/code/local/Oneupweb/ProductColorBox/etc
The config.xml is responsible for wiring up the module. It is used to control layout, models, blocks, and resource configurations (like connection parameters). Since we are only focused on modifying the layout, we will be focusing on the layout portion. Create a file called config.xml and save it in the modules etc folder. Add the following:

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<modules>
		<Oneupweb_ProductColorBox>
			<version>0.1.0</version>
		</Oneupweb_ProductColorBox>
	</modules>
	<global>

	</global>
	<frontend>
		<layout>
			<updates>
				<productcolorbox>
					<file>productcolorbox.xml</file>
				</productcolorbox>
			</updates>
		</layout>
	</frontend>
</config>

But what does it all mean???

modules
This node is boilerplate. It really just contains the name of the module. The version node is for showing version information (surprising I know)
global
This is where model, block and resource configs go
global
This is where model, block and resource configs go
frontend
This is where non-admin layout, and rout configs go; this is where our focus will be

Let’s just make some observations on the layout portion of the xml:

<!-- We have some layout configs -->
<layout>
	<!-- Magento renders "updates" on the backend. Dont worry about it, this will always be here -->
	<updates>
		<!-- Just an identifier for you. You can call it whatever. HotHamSandwich would work -->
		<productcolorbox>
			<!-- The name of the layout file in the theme you are using -->
			<file>productcolorbox.xml</file>
		</productcolorbox>
	</updates>
</layout>

You will notice that our layout config points to a file. What is this file you ask? Onward!

Creating the layout file!

Layout files are used to configure view blocks. We are going to use this handy feature to add our scripts and styles to the product page. The key here is to make your module work with the current theme (not the most pluggable, but magento has ways of deploying this stuff). So let’s add our layout file:
Location:/app/design/frontend/default/layout/

Layouts and templates live in the /app/design folder. Navigate to the above directory (If you are using a different theme it would be /app/design/frontend/YOURTHEME/layout) and create the file we mentioned in our config.xml:productcolorbox.xml

Here is where things get a little tricky. Remember this xml file configures view blocks. From a layout xml file you can reference existing blogs, wire up new ones, and call methods that exist on these blocks. We are going to use our layout xml file to reference the head block on the product view page. Put the following in our productcolorbox.xml file and save:

<?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
	<catalog_product_view>
		<reference name="head">
			<action method="addJs"><script>oneupweb/productcolorbox/jquery-1.6.4.min.js</script></action>
			<action method="addJs"><script>oneupweb/productcolorbox/jquery.colorbox-min.js</script></action>
			<action method="addJs"><script>oneupweb/productcolorbox/init.js</script></action>
			<action method="addCss"><stylesheet>css/colorbox.css</stylesheet></action>
		</reference>
	</catalog_product_view>
</layout>

Let’s dissect each of these nodes:

layout

This is where all your custom layout configurations go for your module. In addition to the top level layout node, you can also use default which targets things that are loaded on every page.

catalog_product_view

This little bit is important. It instructs Magento to load configurations on a specific page. The above pattern is the following: module_controller_action , which essentially pans out to /catalog/product/view. So in our example here we are configuring our blocks for this page, and this page only.

reference

This node allows you to reference an existing block. The name attribute is the name of the block you are referencing. In this case we are referencing the head block.

action

This allows you to call methods on the block you are targeting. The method of the block you are calling is specified in the method attribute. We are calling the addJs method of the Head block in /app/core/Mage/Page/Block/Html/Head.php. You can verify this by opening that file:

/**
* Add JavaScript file to HEAD entity
*
* @param string $name
* @param string $params
* @return Mage_Page_Block_Html_Head
*/
public function addJs($name, $params = "")
{
    $this->addItem('js', $name, $params);
    return $this;
}

Any node passed to the action node is treated as an argument that is passed to the method. We use script and stylesheet here, but it could just as easily be name or silly_hat. Some points to know about the addJs and addCss methods.

addJs adds scripts relative to /app/js
addCss adds stylesheets relative to /skin/frontend/current_interface/current_theme in my case /skin/frontend/default/default

Setup the product template

We have one minor setup here. We are going to modify the product media template to create a simple hook for our JavaScript to use on the product images. The product view template makes a call to include the output from the media template which is located at /app/design/frontend/base/default/template/catalog/product/view/media.phtml. We are going to modify the base template so it shows up in all themes, but you could just as easily recreate this directory structure in your own theme. We are going to modify the portion of this template where the block fetches gallery images for a product. We will be adding an html5 data attribute (don’t worry, these still work in older browsers). Head to the loop of gallery images and make sure it looks like this:

    <?php foreach ($this->getGalleryImages() as $_image): ?>
        <li>
            <a data-url="<?php echo $_image->getData('url'); ?>" href="#" onclick="popWin('<?php echo $this->getGalleryUrl($_image) ?>', 'gallery', 'width=300,height=300,left=0,top=0,location=no,status=yes,scrollbars=yes,resizable=yes'); return false;" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>"><img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(56); ?>" width="56" height="56" alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" /></a>
        </li>
    <?php endforeach; ?>

The only thing we changed was the addition of the data-url attribute which stores the url to the gallery image. We will use this in our JavaScript.

Download libraries and create scripts!

Download our dependencies:

Then create our script folder we laid out in our layout xml and save our scripts to it.
/js/oneupweb/productcolorbox

add the colorbox css and it’s accompanying image folder to our skin css folder as we wired it up in the layout xml.
/skin/frontend/default/default/css

Next create the init.js script in our productcolorbox js folder as mentioned in the layout xml file and paste the following:

//be sure to use noConflict because Magento ships with the prototype library
jQuery.noConflict();
jQuery(document).ready(function(){
	var thumbs = jQuery('.more-views a');
	thumbs.each(function(){
		var anchor = jQuery(this),
			onClck = anchor.attr('onclick'),
			matches = [],
			imageHref = anchor.attr('data-url');

		anchor.removeAttr('onclick');
		anchor.attr('rel','cbox').attr('href',imageHref);
	});
	jQuery('a[rel=cbox]').colorbox();
});

That’s it! You now have a working lightbox for your product galleries and a solid understanding of how to spice up your catalog by adding scripts and styles via your custom modules.

Conclusion

Magento is a highly configurable system. To some it may seem like there are just too many steps (In fact I sit inside this camp), but once you understand the flow of this eCommerce powerhouse, you will be able to effectively develop and extend it with ease. You might find there aren’t as many limitations as you may have first believed.

GD Star Rating
loading...
Development

Oneupweb : Magento Module Development Part 1: Creating the module

Posted by Brian in Development, Freebies, Tutorials on November 11, 2011 - 4:44 pm

Magento is a great eCommerce platform. It is extremely flexible. So flexible in fact that it is hard to know everything that is available to you as a developer. It’s even harder to know because the Magento community seems to keep its craft a secret… documentation is getting better, but it is sparse. Finding examples can be a chore. The best way to start developing extensions for Magento is to hop in and get your feet a little mucky.

In this first article, I am going to talk about what it takes to even get Magento to recognize your custom module.

What files and where?

The most important thing to remember is that the initialization magic happens in the “app” folder of your Magento installation.

Step 1: Create your configuration xml file for the module

Location: app/etc/modules
Let’s go ahead and create our module xml.

<config>
    <modules>
        <Oneupweb_ProductColorBox>
            <active>true</active>
            <codePool>local</codePool>
        </Oneupweb_ProductColorBox>
    </modules>
</config>

Please note the capitalization. It does matter. For example: codePool vs. codepool.
What does this all mean?

Oneupweb_ProductColorBox
The name of our module. This also reflects the path to our module using this pattern:
/app/code/{codePool}/Oneupweb/ProductColorBox where {codePool} is the value supplied to the module xml, in this case local
active
Is this module active, true enough, it is
codePool
Where your module files will reside /app/code/{codePool}

Go ahead and save the file as Oneupweb_ProductColorBox.xml.

Login to the Magento admin and head over to the System tab and click on the Configuration item. From there go to the “Advanced” tab on the left, and click the “Advanced” tab that is inside of that one to verify our module installed correctly:

BOOM. Our module is installed and recognized by Magento. The first battle has been won, but the war is not over!

Step two setup your module directory

As mentioned the directory structure for your module files follows the convention (referencing the module xml file from above):
/app/code/{codePool}/Oneupweb/ProductColorBox *Notice the underscore from the name becomes the directory separator

So go ahead and create the following directories:
/app/code/local/Oneupweb/
/app/code/local/Oneupweb/ProductColorBox

Within this folder we will be adding the typical directories (thought we may not use them all):
/app/code/local/Oneupweb/ProductColorBox/Block/
/app/code/local/Oneupweb/ProductColorBox/etc/
/app/code/local/Oneupweb/ProductColorBox/Helper/
/app/code/local/Oneupweb/ProductColorBox/Model/
/app/code/local/Oneupweb/ProductColorBox/controllers/
If your module does any kind of installation setup like creating tables then you will also have:
/app/code/local/Oneupweb/ProductColorBox/sql/

The following is a brief explanation of what these folders are for:

Block
This is where the Blocks used in managing views for your module will be stored
etc
This is the directory to store configuration xml files like config.xml or system.xml
Helper
Where you store, well…. helpers. Files that will help you manage data, additional functionality…whatever. Loaded with Mage::getHelper()
Model
Where you store data models used in your module. Loaded with Mage::getModel() or Mage::getSingleton()
controllers
Controllers are what handle the requests for your module. They are essential the pages of your module
sql
Contains installation scripts for your modules that need to create tables

Conclusion

This is the first step to getting your module going in Magento. If you want to download the module skeleton created in this chapter, you can grab it here Stay tuned for more in this series as we build our very own Magento module!

GD Star Rating
loading...