Quick Tip: Lock Your SWF to a Specific Domain Name

Do you want to keep your SWF exclusive to your site? In this Quick Tip, we’ll look at how to use a “site lock” to stop people downloading your SWF and embedding it on a different website.


Final Result Preview

Here is the file running on an incorrect domain:

We’ll build an animated display to be activated when the SWF is on the wrong domain, as in the above example. Saying that, if you just want to learn about the site lock code, skip to Step 5.


Step 1: Tweener

Before you get started writing code and adding designs to the stage, you must first get Tweener. For this project I used open source, which can be used for open and commercial projects. Caurina tweener is available a code.google.com.

After you have downloaded Tweener, just copy and paste it to your project folder. Remember, the folder must be named caurina, inside the folder there must be a folder called transitions, and inside of that a load of Flash .as class files.

With the first step done, we can get on with coding and designing the file.


Step 2: File Size and Layers

The file size is irrelevant. Domain locker’s property is to lockdown your SWF, or component, in case someone has downloaded it from you without your permission.

For this example, I have used a stage size of 540 x 400, you can use whatever size you want.

After you’ve selected the file size, create 3 new layers as in the image below. Always keep your Actions Layer empty. Organised stages are much easier to work with and understand.


Step 3: The Censor System

After you have created the 3 layers, create 2 new simple movieclips. Place them wherever you want, whatever size you want. 40 pixel height by 10 pixel width let’s say, with no stroke. Positioning is not important, because we will be placing these movieclips by actionscript later on.

Now, comes the most important aspect of these movieclips, the registration point. Look at the pictures below, when converting your bitmaps to movieclips, remember to do the following else the file will not run at it’s full potential:

And of course, the instance names:

 

Congratulations! You’ve added the boxes that will shut the page down, in case the domain is wrong. Now, add a dynamic text box to the middle of the stage or anywhere you want it to be. This text box will inform the user who downloaded the file illegally that the file is protected by the script.. Give it an instance name of warning_txt


Step 4: Loading Necessary Classes

Now, once you’ve created the movieclips and the text box, you are ready to code. On the locked actions layer, press F9, and add the following code:

import flash.events.*;
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.net.navigateToURL;
import flash.net.URLRequest;
import flash.net.URLVariables;
import caurina.transitions.Tweener
  • flash.events.*; loads all the events we will probably need.
  • flash.display.LoaderInfo; brings up all information we need to load and that will load with the file.
  • flash.flash.display.MovieClip; loads all the events we will come across while using movieclips.
  • import caurina.transitions.Tweener; loads our tween engine, and the animation of the content blocking bars.

The rest of the events loaded are needed so that Flash gets access to the page URL in the bar.


Step 5: Checking for a Specific Page

var url:String = stage.loaderInfo.url;

Let’s suppose the SWF is loaded on the page http://www.domainName.com/siteFolder/sitePage.html. Line 9 retrieves this URL and assigns it to the string called url.


Step 6: Cause and Effect

Now that Flash knows where to get the URL from, it’s time to compare that with our web site’s URL, and take action if they match or don’t

function pageDomainCheckInit(event:Event):void {
	if (url != "http://www.domainName.com/siteFolder/sitePage.html") {

		warning_txt.text="This file is running on the wrong URL. Content Access Restricted!";
		closeBoxTop.x = 0
		closeBoxTop.visible = true;
		closeBoxTop.height= stage.stageHeight/2
		Tweener.addTween(closeBoxTop,{width:stage.stageWidth, alpha: 0.8, time:1, transition:"easeInOutExpo"});

		closeBoxBottom.x = stage.stageWidth
		closeBoxBottom.visible = true;
		closeBoxBottom.height= stage.stageHeight/2
		Tweener.addTween(closeBoxBottom,{width:stage.stageWidth, time:1, alpha: 0.8, transition:"easeInOutExpo"});
	} else {

		warning_txt.text=" ";
		closeBoxTop.visible = false;
		closeBoxBottom.visible = false;
	}
	stage.removeEventListener(Event.ENTER_FRAME, pageDomainCheckInit);
}

stage.addEventListener(Event.ENTER_FRAME, pageDomainCheckInit);

We’ve used an event listener to start the check-up of the previously detected URL string. What this basically does, is tell flash that if the string located in the navigation bar (or the URL where the page is hosted on) is not the correct one, then the page will execute the script of blocking out content and warn the user that the domain is incorrect. Otherwise, if the page is correctly placed, the boxes that close up the page will not be shown, neither will the warning text.

After this section is completed, we remove the event listener so the file does not eat up resources by checking and rechecking and rechecking over and over again. Once the string is successfully pulled, compared, and the script is successfully executed, the pageDomainCheckInit event is removed.

if (url != "http://www.domainName.com/siteFolder/sitePage.html") {

This section of the code, is basically an “IF NOT”, so if the page is not http://www.domainName.com/siteFolder/sitePage.html Flash will start executing functions below the IF, but otherwise – if the SWF is on the correct page – Flash will remove the blocks from stage, and keep everything neat and tidy. You’ll never know it’s there.

Now, let’s see what happens, when the file is not on the right domain.

warning_txt.text="This file is running on the wrong pageDomain. Content Access Restricted!";
closeBoxTop.x = 0
closeBoxTop.visible = true;
closeBoxTop.height= stage.stageHeight/2
Tweener.addTween(closeBoxTop,{width:stage.stageWidth, alpha: 0.8, time:1, transition:"easeInOutExpo"});

closeBoxBottom.x = stage.stageWidth
closeBoxBottom.visible = true;
closeBoxBottom.height= stage.stageHeight/2
Tweener.addTween(closeBoxBottom,{width:stage.stageWidth, time:1, alpha: 0.8, transition:"easeInOutExpo"});

The code you see here, positions the closeBoxes to stage start and stage end (closeBoxTop = 0 , closeBoxBotton = stage.stageWidth), and makes them invisible (closeBoxTop.visible = false, closeBoxBottom.visible = false) this hides them from the stage, keeps them away from view, and does not affect the site’s appearance. Nevertheless, they are there.

If the page, or the component is installed on a different site/domain name which it was not originally intended to be on, they become visible. They expand across the screen, covering it completely and alerting the user that the content is stolen or not where it’s supposed to be.

This measure not only informs the general user that the file is not where it’s supposed to be, but it also blocks out any content from being displayed.


Step 7: Checking for a Specific Domain

What if we only want to check whether the SWF is loaded on a specific domain?

So instead of checking if the SWF is at http://www.domainName.com/siteFolder/sitePage.html, we just check if it’s somewhere on the domainName.com website. So it could be at https://private.domainName.com/secure/secret.html and still work.

We can achieve this by editing the code that gets the URL, like so:

var url:String = stage.loaderInfo.url;		//this line was here before!
var urlBeginning:int = url.indexOf("://") + 3;
var urlTermination:int = url.indexOf("/", urlBeginning);
var pageDomain:String = url.substring(urlBeginning, urlTermination);
var lastDot:int = pageDomain.lastIndexOf(".") - 1;
var CharacterAfterDomain:int = pageDomain.lastIndexOf(".", lastDot) + 1;
pageDomain = pageDomain.substring(CharacterAfterDomain, pageDomain.length);

Code explained

Let’s suppose the SWF is loaded on the page http://www.domainName.com/siteFolder/sitePage.html. Line 9 retrieves this URL and assigns it to the String called url. That’s the same line we had before.

Line 10 of code retrieves the position within the URL of the ://

Line 11 of code retrieves the first / that appears in the URL after the ://. This is actually very important because between these your actual domain name can be found.

Line 12 of code, is just making the connection inside Flash of what’s in between the :// and the first / getting the domain name String ready for checking in the next step. At this point, with our example, pageDomain has been set to www.domainName.com.

The remaining code checks for the domain name string, what is before it (meaning “www” or “http://www.”) and what is after your domain name (meaning the “.”).

All of these are ignored, so that Flash can define the actual domain name. The domainName.com. Instead of checking:

if (url != "http://www.domainName.com/siteFolder/sitePage.html") {

…we check:

if (pageDomain != "domainName.com") {

The main problem with this technique is that it doesn’t work for domains that have three parts. For example, domainName.co.uk – this code will get “.co.uk” as the value of pageDomain. Still, it is my preferred method, as I will explain in the next step.


Step 8: Utility?

You may have several files on your server, on different domains, this method could have been done in such a manner that the file would be locked on one single and unique URL, as above. But if you were to run your file using deep linking for example, or subdomains, the file would stop working, due to the fact that the link would be invalid to the domain reader.

The fact that the code is if (pageDomain != "domainName.com") is very important. It will permit you to add this code to every file on your site, subdomain, deep link location; as long as your link is on that domain, the file will run, and the domain locker will not trigger!

Still, it can be useful to lock to something more specific than a domain name. Suppose you host your web site on a host like Amazon S3. Then your URL will be something like http://yoursitename.s3.amazonaws.com/folder/page.html. But someone else on Amazon S3 could have the URL http://someoneelse.s3.amazonaws.com/. They could upload the SWF to their site, and since the SWF would still be on amazonaws.com the domain locker would not lock.

Tip

Here’s a little tip you might really love. Let’s presume for a moment that you have the same content on several domain names and you don’t want to add a different code for each of your domains. You can make the file check for multiple domains at once really easily.

Meet the OR command: || Using this command inside the first checker you can add as many domains as you wish. Let me show you how! :)

Single domain checker:

(pageDomain!="domainName.com")

Multiple domain checker:

(pageDomain!="domainName.com" || "mydomain.com" || "hisdomain.com") really easy, isn’t it?


Conclusion

Well, this wraps it up. As you all know, full protection of flash files is never guaranteed 100%, but this is just another step, in making your site safer, better, and more secure against file theft. Don’t forget to encrypt your files before adding them to the server! Thanks for reading this tutorial, I hope it was useful to you, if you need any further help, don’t hesitate to leave your questions within the comment section.

Using AS3XLS with the Flex Framework: Data Display Options

This tutorial will cover implementation of the AS3XLS ActionScript 3.0 library for the Flex framework. This time, we’ll demonstrate editable properties of the Flex datagrid and the use of various charting components to display associated data imported from Excel .xls files.


View Screencast

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!

Flash CS5 for Designers: TLF and Hyperlinks + Sample Chapter!

Every type of TLF text in Flash — Read Only, Selectable, and Editable — supports hyperlinks. All it takes to add a link in a text container is to type in your text, select a few words, and enter the desired URL into the Properties panel. Optionally, you can enter a target as well.

The following is an exercise from Foundation Flash CS5 For Designers by Tom Green & Tiago Dias.
 
Congratulations to our three winners who all won a signed copy! And if you weren’t so lucky this time, help yourself to a sample chapter courtesy of FriendsOfEd. Enjoy!

If you want the whole text container hyperlinked, use the Selection tool to select the container itself, and then use the Link and Target properties in the Advanced Character options area of the Properties panel in the same way.

Applying a hyperlink to text

As easy as this approach is, a downside is the hyperlink underline added to the text. It simply can’t be removed. Still, hyperlinks may be absolute, such as http://www.SuperSite.com/thisPageHere.html, or relative, such as../thisOtherPage.html. For relative paths, it’s important to know that the path will be determined not from the point of view of the SWF, but from the HTML file that contains it.

For example, you may choose to keep all your HTML files in the root of your website. Because you’re an organized developer, you may choose to put all your image files in their own subfolder of the root, and you may just do the same with your Flash content. From a SWF’s point of view, the relative path to all HTML files requires stepping back one folder. So, if a SWF links to one of those pages, you might be tempted to precede the destination’s filename with ../, but don’t! The HTML file that contains the SWF in question is already in the same folder as the destination page, and it’s the containing HTML file’s point of view that matters.


Using ActionScript to Add Hyperlinks to TLF Text

As you saw in the previous example, you can use a piece of text in a container to trigger an event on the Flash stage. It goes without saying that the same piece of text can be used to launch a web page. Rather than rehash everything done previously, open the enclosed TLF_Hyperlink_AS.fla file and let’s see how this is accomplished.


Step 1: Select

Scroll down to line 32 of the Script pane.

Select the word NONE, and change it to UNDERLINE. The result of this change is to actually have the clickable text look like a common HTML hyperlink that uses an underline.


Step 2: LinkElement()

Press the Enter (Windows) or Return (Mac) key twice, and enter the following code block:

var link:LinkElement = new LinkElement();
link.href = "http://www.friendsofed.com";
var linkSpan:SpanElement =new SpanElement();
linkSpan.text = "Click here ";
link.addChild( linkSpan);
var span:SpanElement = new SpanElement();
span.text = " to download the files for this book.";
p.addChild(link);
p.addChild(span);
textFlow.addChild(p);

As you may have gathered, all items in a TLF container are influenced or managed by elements. The first two lines establish that a variable called link will be managed by a LinkElement and will be placed in a LinkElement() object. The next line uses the common href tag from HTML to identify the link.

Now that you have established where the link is going — to the friends of ED website — you create a span for the text that will be clicked, put the text into the span, and use the addChild() method to put the linkSpan on the stage.

The rest of the code adds the remaining text, associates the link to the text in the sentence (p), puts the sentence on the stage, and flows it into the textFlow container.


Step 3: Test

Save the file, and test the movie. The text containing the link, as shown below, is blue and sports a rather spiffy underline. Click the link, and the friends of ED homepage opens.

Using the UNDERLINE constant adds the common HTML underline users are used to.

Import Statements Used for This Exercise

These are the import statements used for this exercise:

import flash.display.Sprite;
import flashx.textLayout.container.ContainerController;
import flashx.textLayout.elements.Configuration;
import flashx.textLayout.formats.TextLayoutFormat;
import flashx.textLayout.formats.TextAlign;
import flashx.textLayout.elements.TextFlow;
import flashx.textLayout.elements.ParagraphElement;
import flashx.textLayout.edit.EditManager;
import flashx.undo.UndoManager;
import flashx.textLayout.formats.TextDecoration;
import flashx.textLayout.elements.LinkElement;
import flashx.textLayout.elements.SpanElement;

Open Mike: Brackets

Allman or K&R? This is Open Mike, a series of discussion posts to throw the cat amongst the pigeons. These posts are all about you — we want to hear your opinions, ideas, and thoughts. To kick things off, let’s talk about brackets.


1: Do you Cuddle?

“Cuddling” braces means writing them like this:

function showCuddlingExample():void {
	if (example) {
		//do something
	} else {
		//do something else
	}
}

Alternatively, there’s Allman style:

function showAllmanExample():void
{
	if (example)
	{
		//do something
	}
	else
	{
		//do something else
	}
}

This Wikipedia entry lists other common styles. Which do you use?

I like Allman because you can do this:

//if (someCondition)
{
	doSomething();
}

I can easily turn the conditional check off by simply commenting out the ‘if’ statement. If I was cuddling braces, I’d have to either write a new brace to replace the ‘if’, or comment out the corresponding closing brace.


2: Do You Pad Your Parentheses?

Compare all of these:

//tight
function exampleFunction(arg1:int, arg2:String):void
//space before parentheses
function exampleFunction (arg1:int, arg2:String):void
//space between variable and type
function exampleFunction(arg1 : int, arg2 : String) : void
//padded parentheses
function exampleFunction( arg1:int, arg2:String ):void

I’ve seen all of these, in various combinations. I used to use ‘padded parentheses’, as it seemed easier to see the arguments and their types, but now I prefer ‘tight’. What about you?


3: Do You Nest Parentheses in Conditions?

To me, it feels “correct” to write:

if ( (condition1) || (condition2) )

…rather than:

if (condition1 || condition2)

…even though the first takes up a lot more space. The parentheses make it clear where the separation lies. But is that small distinction worth it?

One last thing: thanks to Sergio from www.artua.com for the awesome microphone icon!

Design and Develop a Fantastic Flash Shooting Gallery Game – Active Premium

Plenty has been happening in the world of Tuts+ Premium lately, so let’s keep the ball rolling with another cracking tutorial exclusively available to Premium members. Here’s a brilliantly entertaining AS3 game tut, courtesy of Carlos Yanez.


Take a look at (and play around with) the final result we will be working towards:


This Premium Tutorial is Packed with Design and Development Tips

Using the Flash Tools we’ll create good looking graphics that will be powered by several ActionScript 3 classes like MouseCursor, Tween Nano, Sprite, Timers and other Events.

The user will be able to input a player’s name and destroy a predefined number of dartboards before the game ends.


Professional and Detailed Instructions Inside

Premium members can Log in and Download! Otherwise, Join Now! Below are some sample images from this tutorial.


Active Premium Membership

We run a Premium membership system which costs $9 a month (or $22 for 3 months!) which periodically gives members access to extra tutorials, like this one! You’ll also get access to Psd Premium, Vector Premium, Audio Premium, Net Premium, Ae Premium and Cg Premium too. If you’re a Premium member, you can log in and download the tutorial. If you’re not a member, you can of course join today!

Also, don’t forget to follow @activetuts on twitter and grab the Activetuts+ RSS Feed to stay up to date with the latest tutorials and articles.

Flash CS5 for Designers: Using TLF Text as a Button

It should come as no surprise that you can use TLF text as a button to kick off an event in your movie. For example, you could have a text block on the stage that talks about a visit to Times Square in New York, and when the user clicks the phrase Times Square, a photo appears on the stage. In this example, you are going to click some text, and a yellow star you will create on the stage starts spinning.

The following is an exercise from Foundation Flash CS5 For Designers by Tom Green & Tiago Dias.
 
If you’re feeling lucky, enter the Activetuts+ competition to win 1 of 3 signed copies! (Of course, you can always purchase one from FriendsOfEd..)

Step 1: New Document

Open a new Flash ActionScript 3.0 document, and save it as TLF_eventLink_AS.fla. Change the name of Layer 1 to Star, and add a new layer named actions.


Step 2: Select Polystar Tool

Click once in the first frame of the Star layer. Click and hold on the Rectangle tool on your toolbar, and select the Polystar tool.


Step 3: Mellow Yellow

In the Properties panel, twirl down the Fill and Stroke properties and set the Stroke value to None and the Fill value to Yellow (#FFFF00).


Step 4: Star

Twirl down the Tool Settings, and click the Options button to open the Tool Settings dialog box shown in Figure 6-26. Select Star from the Style drop-down, and enter 5 for the Number of Sides. Click OK to close the dialog box.

Use the PolyStar tool to create stars.


Step 5: MovieClip

Draw a star somewhere in the bottom half of the stage, convert it to a movie clip named Star, set its registration point to Center, and in the Properties panel give the Star movie clip the Instance name of starMC.


Step 6: Actions

Click the first frame of the actions layers, and open the Actions panel. When the panel opens, click once in the Script pane, and enter the following code block:

var containerSprite:Sprite = new Sprite();
this.addChild( containerSprite );
containerSprite.x  = 25
containerSprite.y = 50;

A Sprite is a virtual movie clip with no timeline. We start by creating a Sprite named containerSprite, which will be used to hold the text. The reason we need this is because there is going to be some interactivity involved. This Sprite is placed 25 pixels from the left edge of the stage and 50 pixels from the top.


Step 7: Configuration()

Press the Enter (Windows) or Return (Mac) key twice, and enter the following code:

var container :ContainerController = new ContainerController( containerSprite, 400, 300);</p>var config :Configuration = new Configuration();
var charFormat:TextLayoutFormat= new TextLayoutFormat();
charFormat.fontFamily= "Arial, Helvetica,_sans";
charFormat.fontSize = 14;
charFormat.color = 0X000000;
charFormat.textAlign = TextAlign.LEFT;
config.textFlowInitialFormat = charFormat;

Nothing new here. The container for the text is created along with the Configuration() object, and the formatting for the text to be placed in the container is created.


Step 8: linkHoverFormat

Press the Enter (Windows) or Return (Mac) key twice, and enter the following:

var textFlow :TextFlow = new TextFlow();
var p :P aragraphElement  = new ParagraphElement();
p.linkHoverFormat  = { color:0XFF0000 };
p.linkNormalFormat = { color:0x0000FF,textDecoration:TextDecoration.NONE };

The last two lines are new, and their purpose is to let you change the color of a word or group of words when the user rolls over them. The linkHoverFormat property belongs to the TextFormat class and is used to tell Flash what color the text identified as a link will be when the mouse rolls over it. In this case, the color will change to Red.

As you may have guessed, the second line tells Flash what color the link is to be when the mouse rolls off. In this case, it will be blue. Naturally, links are traditionally underlined. The way the underline is removed is to use the NONE constant, which is part of the TextDecoration class. If you want the underline, it would be TextDecoration.UNDERLINE.

The next step in the process is to tell Flash what to do when the colored text is clicked.


Step 9: Click

Press the Enter (Windows) or Return (Mac) key twice, and enter the following:

var link:LinkElement = new LinkElement();
link.addEventListener(FlowElementMouseEvent.CLICK, linkClicked);

There is, of course, nothing to click. Let’s deal with that issue.


Step 10: Span

Press the Enter (Windows) or Return (Mac) key a couple of times, and add the following:

var linkSpan:SpanElement = new SpanElement();
linkSpan.text = "Click here" ;
link.addChild(linkSpan);

var span:SpanElement = new SpanElement();
span.text = " to see your star spin on the stage";
p.addChild(link);
p.addChild(span);

The next step is to get the text flowing into the container.


Step 11: Spin

Press the Enter (Windows) or Return (Mac) key, and add the following:

textFlow.addChild(p);
textFlow.flowComposer.addController(container);
textFlow.flowComposer.updateAllControllers();

The final code bit is the function that gets the star spinning when the text is clicked. Enter the following:

function linkClicked(evt:FlowElementMouseEvent) :void{
   evt.preventDefault();
   var tween :Tween = new Tween( starMC, "rotation", Elastic.easeOut, 0, 180, 2, true);
}

The first line of code tells Flash to ignore any default settings there might be in regards to the mouse and the text in the container.

The magic happens in that second line. The parameters tell the Tween class to work with the rotation property of the star (starMC) and to apply an easeOut to the star when it finishes rotating. Naturally, Flash, being stupid, needs to be told that the rotation starts with the star at 0 degrees and to rotate across 180 degrees. It does this two times and uses seconds as the measure of time.


Step 12: Error Checking

Click the Check Syntax button as your first skim through the code looking for errors. If there are none, your computer will ding. If errors are found, they will be shown in the Compiler panel. The most common error will be spelling or a missing import statement.

Here’s a quick tip. If a class doesn’t show up as an import, the Compiler panel will tell you the property is undefined. Select the class in the code where it appears, and delete the text. Type in the first two letters of the class, and press Ctrl+spacebar. The class will appear in the resulting code hint. Double-click the class to add it back into the code. This also creates the missing import statement.


Step 13: Save and Test the Movie

The text is colored. When you click the mouse, the star spins. A completed version of this file is included with the source download.

Import Statements for This Exercise

These are the import statements for this exercise:

import flash.display.Sprite;
import flashx.textLayout.container.ContainerController;
import flashx.textLayout.elements.Configuration;
import flashx.textLayout.formats.TextLayoutFormat;
import flashx.textLayout.elements.TextFlow;
import flashx.textLayout.elements.ParagraphElement;
import flashx.textLayout.elements.LinkElement;
import flashx.textLayout.elements.SpanElement;
import flashx.textLayout.events.FlowElementMouseEvent;
import fl.transitions.Tween;
import flashx.textLayout.formats.TextDecoration;
import fl.transitions.easing.Elastic;
import flashx.textLayout.formats.TextAlign;

Franci’s FITC San Francisco Diary: Day Two

By day two at FITC it had become obvious to me that I had underestimated Flash as a tool for deploying all sorts of interactive digital experiences on the desktop as well as in public. It seems you have to see and hear first hand the different logic and technologies that go into creating these experiences to actually realize that you might be able to pull it off yourself..

I’m talking about most of us who have experience with Flash and AS3 and a bit of extra creativity in store. FITC has given me a fresh set of ideas and opened up a new playground I can experiment in.

fitc


Harnessing the Abundance
Mike Creighton

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!

Flow is the mental state of operation in which a person in an activity is fully immersed in a feeling of energized focus, full involvement, and success in the process of the activity.

The goal of Mike Creighton was to capture the “data” that an artist produces in this Flow state through tracking the motion of analogue painting or drawing, and use that data to create derivative digital work. Flow is the result. It’s a open source project that provides a set of tools for capturing motion data.

It is one of the examples of how Flash has evolved from humble beginnings into a tool which, if properly used and combined with other technologies, allows you to express yourself in ways that were out of the scope of creatives until lately.

The key to being able to create and approach problem solving when working with multiple technologies is defining your goals and setting your parameters, else the abundance can really start working against you. The problem being, that with so many options and interesting steps and results in the process of developing and creating one can be easily distracted from the initial goal. So if you’re not just experimenting or playing around, define your goals and parameters, then stick to them. This was one emphasis of Mike’s presentation.


Space Invading
Seb Lee-Delisle

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!

“Space Invading” was all about bringing the playful, creative experience that Flash can deliver, to the people. Seb is a master of presentations; he connects with his audience with the use of interactive technology and has everyone jumping around in no time. You don’t see that every day, although I do think I need to start going to more of these Flash events.

He had a little presentation of the great work of his studio Plugin-Media along with some of his personal experiments in the beginning. He then went on to demonstrate his live audio/video mixer. The idea is that you can sample sounds and capture video at the same time, map them to different keys on the keyboard and then play them back by pressing those keys. The result is impressive. It’s probably useless for any kind serious recording, but has a lot of other possible creative applications and it’s just plain fun.


The Apparat
Joa Ebert

This presentation was more technical and honestly mostly beyond my comprehension. That doesn’t mean that I won’t be able to use the tools presented to optimize my projects.

Apparat is a set of tools that you can use to further compress your SWF, SWC and ABC files. Particularly if you use the [Embed] method to embed large PNGs and use the Reducer which is one of the Apparat tools, you’ll see a big improvement in your SWF file sizes since it will compress the otherwise uncompressed raw PNG files. This will give you a great reduction in file size reaching over 50% of the original file size, depending on the size and number of embedded PNGs as well as the compression level set by the Reducer. You should check this one out , it will definitely help you streamline your files and reduce bandwidth usage, loading times etc., which can only be a good thing.


Eyes Can Hear, 5 Ways
Jared Ficklin

There may or may not be smoke, fire, lasers & non-newtonian fluids

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!

Everyone probably knows to some degree what sound visualization is, but we don’t really recognize the simple elegance behind it. Seeing Jared do “analog” sound visualizations with smoke, fire and corn starch (yes…corn starch) and then jumping to sound visualization on the screen and in public, you start appreciating the link between the two.

For me it’s easier to understand the workings of a drum shooting smoke rings by sound pressure waves than frequencies, ranges, cutoffs etc.. But mostly it gives me a tangible real world representation of what we’re trying to achieve with sound visualization on the screen and it makes it that more interesting and understandable.

Full video of this presentation available at the FITC web site!


Pulsatile Crackle
André Michelle

If you’re into audio, you should really check out Audiotool. It’s an online Flash application that lets you create and mix music without any installing or registering. Besides it being a great free tool, it’s also testament to Flash’s capabilities as an online runtime environment. It has also been greatly optimized by using the previously mentioned Apparat framework.

There are a lot of interesting creative uses with mixing sound and interactive experience. Using audio in combination with other innovations in Flash like 3D and physics is something that everyone should consider exploring to add that extra edge to their projects.


High Performance Mobile Content with Flash
Mike Chambers

Flash is slowly but surely reaching most of our mobile devices. There is a lot of debate about performance of the Flash player on mobile and even though I’m pretty sure most of us were surprised by how well it performs in general, there are some pretty simple practices that can help you increase performance of your applications without compromising looks or functionality. The following tips apply to both AIR and Flash on mobile devices.

Layout for Silverlight User Interfaces

Silverlight lays out user interface elements in Panels with various capabilities ranging from fixed, pixel-based layout through to flexible, fluid designs. You can make use of the existing layout mechanisms or build your own Panels to supplement what’s available. Let’s take a look at what’s involved..

In this video, we’ll examine the Panels available and the various properties around alignment and sizing that come into play when you’re laying out elements for Silverlight UI.


What’s Covered?

Here’s a quick look at some of the subjects covered in this screencast:

  • Element properties
  • Panel types
  • Dragging and dropping
  • Fixed and fluid layouts

View Screencast

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Useful Links

Mike Taulty Microsoft (UK): http://mtaulty.com: [email protected]: twitter.com/mtaulty

Flash CS5 for Designers: TLF and ActionScript + Win 1 of 3 Signed Copies!

A lot has changed between how text was handled in Flash CS4 and Flash CS5. We think now is a good time to pull up a stool, sit down, and review, in very broad terms, what one needs to know about TLF before “wiring up” an exercise or project using ActionScript.

The following is an exercise from Foundation Flash CS5 For Designers by Tom Green & Tiago Dias.
 
If you’re feeling lucky, enter the Activetuts+ competition to win one of 3 signed copies! (Of course, you can always purchase a copy..)

Introduction

With the new TextLayoutFramework (TLF), text is found in these things called containers. They either can be physically drawn on the stage using the Text tool and given an instance name or, as is more common, can be created at runtime. You also know that the text can be formatted and manipulated using the Properties panel. The neat thing here is the word properties. If there is a property in the panel, its counterpart is found in ActionScript. The bad news is, ActionScript is stone, cold stupid. It doesn’t have a clue, for example, what a container is until you tell it to create one. It won’t format text until you tell it what to do. It won’t even put the text on the stage until it is told to do so.

Most projects will start with you telling Flash to create a Configuration() object, which is used to tell Flash there is a container on the stage and how to manage the Text Layout Framework for the stuff in the container. The actual appearance is handled by the TextFlow() class, which takes its orders, so to speak, from the Configuration() object.

Naturally, being stupid, the Configuration() object needs to be told exactly how to manage the text in the container. The default format is set through a property of the Configuration class called textFlowInitialFormat. To change it, you simply use the TextlayoutFormat () class to set the fonts, colors, alignment, and so on, and then tell the boss—Configuration ()—that its textFlowInitialFormathas changed to the ones you set using TextLayoutFormat().The boss will get that, but he isn’t terribly bright, so you next need to tell him to hand the actual work to another member of the management team, the TextFlow() class. This class has overall responsibility for any words in a container. Being just as dim as the boss, TextFlow() needs to be told what a paragraph is (ParagraphElement), how wide the paragraph is (SpanElement), whether any graphics are embedded in the paragraph (InLineGraphicElement), whether any of the text contains links (Link Element), and so on. Not only that, but it needs to be told what text is being added to the container so it can handle the line length and to add any children (addChild) that contain that formatting so the user can actually see it.

The TextFlow() class, again not being too terribly bright, will then hand the job over to another member of the management team, the IFlowComposer() class, whose only job is to manage the layout and display of the text flow within or among the containers. The flow composer finishes the process by deciding how much text goes into a container and then adds the lines of text to the sprite. This is accomplished through the use of the addController() method, which creates a ContainerController() object whose parameters identify the container and its properties.

The usual last step is to tell the FlowComposer to update the controllers and put the text on the stage according to how the other members of the team have told the Configuration() object how their piece of the project is to be managed.

With this information in hand, let’s move on to working with TLF in ActionScript. We’re going to create a column of text with ActionScript.


Step 1: New Document

Open a new Flash ActionScript 3.0 document, rename Layer 1 to actions, select the first frame of the actions layer, and open the Actions panel.


Step 2: ActionScript

Click once in the Script pane, and enter the following:

var myDummyText:String = "The introduction of the Adobe CS5 product line puts some powerful typographic tools in your hands—notably, a new API (Application Programming Interface) called Type Layout Framework (TLF)—and with as more tools in the Adobe line up nudge closer to a confluence point with Flash, the field of typographic motion graphics on the Web is about to move into territory that has yet to be explored. To start that exploration, you need understand what type is in Flash and, just as importantly, what you can do with it to honor the communication messengers of your content.";

You need some text to add to the stage. This string is the third paragraph of this chapter. Now that you have the text to go into the container, you need to load the class that will manage it.


Step 3: Configuration()

Press the Enter (Windows) or Return (Mac) key, and add the following line of code:

var config:Configuration = new Configuration();

As you may have noticed, as soon as you created the Configuration() object, Flash imported the class—flashx.textLayout.elements.Configuration —whose primary task is to control how TLF behaves. The next code block tells TLF how the text will appear on the stage.


Step 4: TextLayoutFormat Class

Press the Enter (Windows) or Return (Mac) key twice, and enter the following:

var charFormat:TextLayoutFormat = new TextLayoutFormat();
   charFormat.fontFamily = "Arial, Helvetica, _sans";
   charFormat.fontSize = 14;
   charFormat.color = 0x000000;
   charFormat.textAlign = TextAlign.LEFT;
   charFormat.paddingLeft =100;
 charFormat.paddingTop = 100;

The TextLayoutFormat class, as we said earlier, is how the text in a container is formatted. The properties in this class affect the format and style of the text in a container, a paragraph, or even a single line of text. In this case, we are telling Flash which fonts to use, the size, the color, how it is to be aligned (note the uppercase used for the alignment), and the padding that moves it off the edges of the container.

Before you move on, you need you to do something. There is a coding issue. Scroll up to the import statements. If you see this line—import flashx.textLayout.elements.TextAlign;—proceed to the next code block. If you don’t, delete this line in the code block just entered: charFormat.textAlign = TextAlign.LEFT;. Reenter charFormat.textAlign =. Type in the first two letters of the class (Te), press Ctrl+spacebar, and the code hint should appear. Find TextAlign, and double-click it. This should add the missing import statement. To preserve your sanity, we will be providing a list of the import statements that should appear at the end of each exercise. We strongly suggest that you compare your list of import statements against the list presented and, if you are missing any, add them into your code.

Now that you know how the text will be formatted, you need to tell the Configuration() object to use the formatting. If you don’t, it will apply whatever default setting it chooses.


Step 5: textFlowInitialFormat

Press the Enter (Windows) or Return (Mac) key twice, and enter the following:

config.textFlowInitialFormat = charFormat;

Step 6: TextFlow ()

Press the Enter (Windows) or Return (Mac) key, and enter the following code block:

var textFlow:TextFlow = new TextFlow( config );
   var p:ParagraphElement = new ParagraphElement();
   var span:SpanElement = new SpanElement();
   span.text = myDummyText;
   p.addChild( span );
 textFlow.addChild( p );
 

The TextFlow () object needs to be here because its job is to manage all the text in the container. The constructor—TextFlow (config)—lets TLF know that it is to use the config object created earlier so it now knows how to format the contents of the container and even the container itself.
The next constructor—ParagraphElement()—essentially tells Flash how a paragraph is to be handled. There is only one here, so it really doesn’t need a parameter.

The final step is to get all the formatting and layout into the container on the stage.


Step 7: ContainerController

Press the Enter (Windows) or Return (Mac) key, and add these final two lines:

textFlow.flowComposer.addController( new ContainerController( this, 500, 350 ) );
 textFlow.flowComposer.updateAllControllers();

The first line adds the ContainerController and tells Flash the container being managed is the current DisplayObject (this), which currently is the stage, and to set its dimensions to 500 pixels wide by 350 pixels high.


Step 8: Test

Save the project, and test the movie. The text, as shown below, appears using the formatting instructions you set.

Import Statements for this Exercise

These are the import statements for this exercise:

   import flashx.textLayout.elements.Configuration;
   import flashx.textLayout.formats.TextLayoutFormat;
   import flashx.textLayout.formats.TextAlign;
   import flashx.textLayout.elements.TextFlow;
   import flashx.textLayout.elements.ParagraphElement;
   import flashx.textLayout.elements.SpanElement;
   import flashx.textLayout.container.ContainerController;

Using ActionScript to create and format the container and its text

Though this coding task may, at first, appear to be a rather convoluted process, we can assure it isn’t; it will become almost second nature as you start using ActionScript to play with text in the containers.

With the introduction of the Text Layout Format, your ability to create text, format text, put it in columns, and generally manipulate it using ActionScript has greatly expanded your creative possibilities. Before you get all excited about this, you need to know that the word Framework is there for a reason.

Any TLF text objects you create will rely on a specific TLF ActionScript library, also called a runtime shared library (RSL). When you work on the stage in the Flash interface, Flash provides the library. This is not the case when you publish the SWF and place it in a web page. It needs to be available, much like Flash Player, on the user’s machine. When the SWF loads, it is going to hunt for the Library in three places:

  • The local computer: Flash Player looks for a copy of the library on the local machine it is playing on. If it is not there, it heads for Adobe.com.
  • Adobe.com: If no local copy is available, Flash Player will query Adobe’s servers for a copy of the library. The library, like the Flash Player plug-in, has to download only once per computer. After that, all subsequent SWF files that play on the same computer will use the previously downloaded copy of the library. If, for some reason, it can’t grab it there, it will look in the folder containing the SWF.
  • In the folder containing the SWF: If Adobe’s servers are not available for some reason, Flash Player looks for the library in the web server directory where the SWF file resides. To provide this extra level of backup, manually upload the library file to the web server along with your SWF file. We provide more information around how to do this in Chapter 15.

    When you publish a SWF file that uses TLF text, Flash creates an additional file named textLayout_X.X.X.XXX.swz (where the Xs are replaced by the version number) next to your SWF file. You can optionally choose to upload this file to your web server along with your SWF file. This allows for the rare case where Adobe’s servers are not available for some reason. If you open the file where you saved this exercise, you will see both the SWF and, as shown in Figure 6-25, the SWZ file.

The .swz file contains the Text Layout Framework.


The Giveaway!

We’re running this giveaway a little differently since Adam from Aetuts+ pushed Wildfire my way.. Wildfire is a brilliant promotion builder and makes entering competitions a piece of cake! If you’d like to be in with a chance of winning one of three signed copies of “Foundation Flash CS5 for Designers”, just enter!

How do I Enter?

  1. Send a tweet from the entry page. For every Twitter follower that enters through your link you get an extra entry.
  2. Fill in your details once you’ve done so. That’s it!

The three winners will be announced on Monday 6th September. Good luck!

Introducing the Tuts+ Marketplace – Making Premium Accessible to Everyone

We’ve just launched the Tuts+ Marketplace, where Premium quality tutorials – both from our Tuts+ Premium program and from unaffiliated authors – are available to purchase individually. Our Tuts+ Premium program will still stay exactly the same – you’ll get all the same things, for the same price. But now, non-members will be able to purchase selected Premium tutorials on a one-off basis, without a Premium membership.



Hey! Look for this link!

So far we’ve added nearly half our Premium tutorials to the Tuts+ Marketplace, and will be adding more over time. To find out if a Premium tutorial is available for sale on the Tuts+ Marketplace, look for this link:

Item Link

Q + A More Information

Here are answers to some of your likely questions about the Tuts+ Marketplace. Please read through these, and if you have any more questions they may be answered in the special edition podcast Introducing the Tuts+ Marketplace (with me and Sean Hodge as a special guests :) hehe). If not, leave a comment!


QWhat does this mean for Premium members?

That it’s a lot easier to see the value you’re getting as part of Premium. With files on the marketplace priced between $3 and $7, your Premium subscription gives you access to thousands of dollars worth of files for $9 a month. Premium will still work exactly the same and cost the same – so you’ve got nothing to worry about! The marketplace is more for people who aren’t Premium members, and for those who want access to user-submitted tutorials that aren’t available as part of Premium – or anywhere else.


QWhat will be sold on the Tuts+ Marketplace?

We’ve seeded the site with our Tuts+ Premium tutorials, but anyone can submit a tutorial for sale on the Tuts+ Marketplace. If it’s ‘Premium’ quality, it will be accepted. Eventually, the marketplace will be filled with tutorials you can’t find anywhere else.


QWho benefits from the Tuts+ Marketplace?

If you only have time to go through 1 or 2 Premium tutorials a month, or only want to pay for the Premium tutorials you need, the Tuts+ Marketplace is perfect for you. You can purchase tutorials on a one off basis, and files are priced between $3 – $7.

As the marketplace grows, authors will come in from elsewhere to sell their tutorials. There will be high-quality tutorials on the Tuts+ Marketplace that you can’t get anywhere else, so if you love learning from great tutorials, you should keep tabs on the Tuts+ Marketplace.

If you go through lots of Premium tutorials, the Tuts+ Premium subscription is better value for you. The option that’s right for you will depend on your needs.


QWhat categories does the marketplace cover?

We currently host the following categories, and will be expanding our selection over time:



Forums Have your say!

Because the Tuts+ Marketplace is built on our Envato Marketplaces app, we have dedicated Forums. Head on over, sign up for the marketplaces, and tell us what you think of the Tuts+ Marketplace.

5 Resources for Crowdsourcing Creatives

If you’ve ever been the position of needing a logo, a brochure or even a name for your new product, you know the value of having a sharp, creative mind at your disposal. But what if you had thousands? By the same token, what if you’re the person who always wins accolades for doodling logos and thinking up taglines on the fly, but you have no clue how to parlay your talents into work?

The answer is crowdsourcing.

A number of firms have sprung up around the idea of pooling both talent and ideas together into virtual creative marketplaces. The result? Companies save time and money pursuing creative solutions, and writers and designers enjoy low barriers for entry into the process.

Here are some of the major players on the scene:

crowdSPRING

One of the heavyweights in the crowdsourced creative field, crowdSPRING boasts a pool of more than 67,000 writers and designers ready to tackle anything from logo design to product naming.

99Designs

Touting more than 76,000 designers among its ranks, 99Designs focuses exclusively on design, including WordPress templates, t-shirts and stationery alongside the more traditional logos and icons.

Brandstack

This company offers two options: you can peruse their marketplace of designs and purchase directly from the designer, or you can use their premium service Upstack to hire designers for custom work.

Genius Rocket

Genius Rocket offers a wide range of creative services, including video and animation creation.

BootB

BootB brings a whimsical approach and international flavor to crowdsourcing creative challenges for both brands and creators.

Do you have any resources that you use that we didn’t cover here?  Let us know in the comments.

Quick Tip: When and How to Use a Neutral Density Filter

We’re continuing our investigation of camera filters this week, taking a look at Neutral Density filters and Graduated ND Filters. These give you a large degree of control over the exposure in an image, and are brilliant for water and landscape photography.


What Does a Neutral Density Filter Do?

A Neutral Density filter allows a photographer to control the exposure in an image very easily. The filter stops light reaching the camera sensor, therefore allowing us to leave the camera with a higher aperture for a longer amount of time.

Instead of changing the aperture to reduce the amount of light in the image, we simply add on a ND filter, then adjust the exposure to the amount we want. It is easy and very effective, plus we can still set the aperture to a low value for sharper images, or wide open for a shallow DOF.

ND filters do not effect the colour in the photo in any way. What you see is what you get. This is a big difference compared to the Polarizer filter.

Photographers commonly use a ND filter when shooting water as it blurs the moment, and you get a smooth silky look. Without the ND filter, most cameras are unable to find an aperture small enough to get the same effect.

Other helpful uses of ND filters include:

  • Reducing the depth of field in bright sunlight
  • Adding motion blur to moving objects
  • When using a wider aperture

Image courtesy of TropicaLiving


What Is a Graduated Neutral Density Filter?

It’s the same as a ND filter, but graduated! This simply means that the ND effect is not on the whole of the glass, it fades gradually as the name suggests.

This is useful because photographers often want to darken the sky, but leave the foreground as it is. To do this you simply move the filter up and down in the holder to match the landscape you are shooting.

Disadvantages of using a graduated filer include the fact that often the landscape is not flat like the straight edge on the filter.

You can buy different graduated ND filters depending on the effect you are after. You can get a soft edge which has a large fading distance or a hard-edge with a sharper quicker fade.

The image below shows a use of a graduated filter. The left photo has no filter attached but the image on the right has a 2 stop Grad ND filter. As you can see the sky shows up perfectly.

Image courtesy of Jez B


What Different Types Are There?

You can get different strength ND filters to block out more light than others. This is very useful, but also requires you to buy more expensive filters, as well as know this very large F stop chart pictured below (click for larger version)

The most common kinds are a 1 stop, 2 stop and 3 stop filter. You can also purchase a 10 stop filter if you really want to slow things down. If you don’t understand f stops, check out Phototuts+ Basix tutorial!

An example would be if you are shooting at f11 with a speed of 1/500, then decided to use a 10 stop filter with the same aperture then you’ll get an exposure of 2 seconds. This is quite a large jump and you will need to use a tripod no matter what.

If you are using a filter holder remember you can double the filters up. So you can put a 3 stop and 2 stop on top of each other. Useful, but beware of vignette around the final image.

Image courtesy of David M71


Recommended Brands

LEE filters:

Cokin:

Hoya:

Dolica:

The LEE filter is aimed at professionals and has the price tag to match but if you are looking to try out playing with ND filters why not pick up a cheaper set made by Dolica? Good quality for the money and they work a treat.


Further Reading

If you have found the subject interesting then you might want to take a look at these articles:

Image courtesy of djniks


Thanks for Reading

If you own a ND filter please post up your photos – we always take the time to view them all. Also, if you would like information on any other filters, please feel free to leave a comment with your question!

Friday Photo Critique #49

Friday Photo Critique is our weekly community project, where we publish a photograph submitted by one of our wonderful readers, then ask you all to offer constructive feedback on the image. It’s a great way to learn more about photography, express your viewpoint, and have your own image critiqued!


Quick Ground Rules

  1. Play nice! We’ve deliberately chosen photographs that aren’t perfect, so please be constructive with any criticism.
  2. Feel free to offer any type of advice – composition, lighting, post-processing etc.
  3. You can also link to photographs that you feel offer a great example of this type of image shot exceptionally well.

Without further ado, here is this week’s candidate for Friday Photo Critique!


The Photograph

Photo Critique

Photographer: Steven Davis

Please let us know what you think in the comments – how would you have approached the scene or taken the photo differently? A massive thank you to everyone who commented last week.

The most constructive and helpful comments will be featured on the site. Interested in submitting your own photo? You can do so here!

Understanding and Applying Polymorphism in PHP































In object oriented programming, polymorphism is a powerful and fundamental tool. It can be used to create a more organic flow in your application. This tutorial will describe the general concept of polymorphism, and how it can easily be deployed in PHP.


What is Polymorphism?

Polymorphism is a long word for a very simple concept.

Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.

The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way.

A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.

In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.


Interfaces

An integral part of polymorphism is the common interface. There are two ways to define an interface in PHP: interfaces and abstract classes. Both have their uses, and you can mix and match them as you see fit in your class hierarchy.

Using an Interface

An interface is similar to a class, except that it cannot contain code. It can define method names and arguments, but not the contents of the methods. Any classes implementing an interface must implement all methods defined by the interface. A class can implement multiple interfaces.

An interface is declared using the ‘interface‘ keyword:

interface MyInterface {
    // methods
}

and is attached to a class using the ‘implements‘ keyword:

class MyClass implements MyInterface {
    // methods
}

Methods can be defined in the interface just like in a class, except without the body (the part between the braces):

interface MyInterface {
    public function doThis();
    private function doThat();
    public function setName($name);
}

All methods defined here will need to be included in any implementing classes exactly as described. (Note the code comments below.)

// VALID
class MyClass implements MyInterface {
    protected $name;
    public function doThis() {
        // code that does this
    }
    private function doThat() {
        // code that does that
    }
    public function setName($name) {
        $this->name = $name;
    }
}

// INVALID
class MyClass implements MyInterface {
    // missing doThis()!
    public function doThat() {
        // this should be private!
    }
    public function setName() {
        // missing the name argument!
    }
}

Using an Abstract Class

An abstract class is a mix between an interface and a class. It can define functionality as well as interface (in the form of abstract methods). Classes extending an abstract class must implement all of the abstract methods defined in the abstract class.

An abstract class is declared the same way as classes with the addition of the ‘abstract‘ keyword:

abstract class MyAbstract {
    // methods
}

and is attached to a class using the ‘extends‘ keyword:

class MyClass extends MyAbstract {
    // class methods
}

Regular methods can be defined in an abstract class just like in a regular class, as well as any abstract methods (using the ‘abstract‘ keyword). Abstract methods behave just like methods defined in an interface, and must be implemented exactly as defined by extending classes.

abstract class MyAbstract {
    protected $name;
    public function doThis() {
        // do this
    }
    abstract private function doThat();
    abstract public function setName($name);
}

Step 1: Identify The Problem

Let’s imagine that you have an Article class that is responsible for managing articles on your website. It contains information about an article, including the title, author, date, and category. Here’s what it looks like:

class poly_base_Article {
    public $title;
    public $author;
    public $date;
    public $category;

    public function  __construct($title, $author, $date, $category = 0) {
        $this->title = $title;
        $this->author = $author;
        $this->date = $date;
        $this->category = $category;
    }
}

Note: The example classes in this tutorial use the naming convention of “package_component_Class.” This is a common way to separate classes into virtual namespaces to avoid name collisions.

Now you want to add a method to output the information into different formats, such as XML and JSON. You might be tempted to do something like this:

class poly_base_Article {
    //...
    public function write($type) {
        $ret = '';
        switch($type) {
            case 'XML':
                $ret = '<article>';
                $ret .= '<title>' . $obj->title . '</title>';
                $ret .= '<author>' . $obj->author . '</author>';
                $ret .= '<date>' . $obj->date . '</date>';
                $ret .= '<category>' . $obj->category . '</category>';
                $ret .= '</article>';
                break;
            case 'JSON':
                $array = array('article' => $obj);
                $ret = json_encode($array);
                break;
        }
        return $ret;
    }
}

This is kind of an ugly solution, but it works — for now. Ask yourself what happens in the future, though, when we want to add more formats? You can keep editing the class, adding more and more cases, but now you’re only diluting your class.

One important principle of OOP is that a class should do one thing, and it should do it well.

With this in mind, conditional statements should be a red flag indicating that your class is trying to do too many different things. This is where polymorphism comes in.

In our example, it is clear that there are two tasks presented: managing articles and formatting their data. In this tutorial, we will refactor our formatting code into a new set of classes and discover how easy it is use polymorphism.


Step 2: Define Your Interface

The first thing we should do is define the interface. It is important to think hard about your interface, because any changes to it may require changes to calling code. In our example, we’ll be using a simple interface to define our one method:

interface poly_writer_Writer {
    public function write(poly_base_Article $obj);
}

It’s that simple; we have defined a public write() method that accepts an Article object as an argument. Any classes implementing the Writer interface will be sure to have this method.

Tip: If you want to restrict the type of arguments that can be passed to your functions and methods, you can use type hints, as we’ve done in the write() method; it only accepts objects of type poly_base_Article. Unfortunately, return type hinting is not supported in current versions of PHP, so it is up to you to take care of return values.


Step 3: Create Your Implementation

With your interface defined, it is time to create the classes that actually do stuff. In our example, we have two formats that we want to output. Thus we have two Writer classes: XMLWriter and JSONWriter. It’s up to these to extract the data from the passed Article object and format the information.

Here’s what XMLWriter looks like:

class poly_writer_XMLWriter implements poly_writer_Writer {
    public function write(poly_base_Article $obj) {
        $ret = '<article>';
        $ret .= '<title>' . $obj->title . '</title>';
        $ret .= '<author>' . $obj->author . '</author>';
        $ret .= '<date>' . $obj->date . '</date>';
        $ret .= '<category>' . $obj->category . '</category>';
        $ret .= '</article>';
        return $ret;
    }
}

As you can see from the class declaration, we use the implements keyword to implement our interface. The write() method contains functionality specific to formatting XML.

Now here’s our JSONWriter class:

class poly_writer_JSONWriter implements poly_writer_Writer {
    public function write(poly_base_Article $obj) {
        $array = array('article' => $obj);
        return json_encode($array);
    }
}

All of our code specific to each format is now contained within individual classes. These classes each have the sole responsibility of handling a specific format, and nothing else. No other part of your application needs to care about how these work in order to use it, thanks to our interface.


Step 4: Use Your Implementation

With our new classes defined, it’s time to revisit our Article class. All the code that lived in the original write() method has been factored out into our new set of classes. All our method has to do now is to use the new classes, like this:

class poly_base_Article {
    //...
    public function write(poly_writer_Writer $writer) {
        return $writer->write($this);
    }
}

All this method does now is accept an object of the Writer class (that is any class implementing the Writer interface), call its write() method, passing itself ($this) as the argument, then forward its return value straight to the client code. It no longer needs to worry about the details of formatting data, and it can focus on its main task.

Obtaining A Writer

You may be wondering where you get a Writer object to begin with, since you need to pass one to this method. That’s up to you, and there are many strategies. For example, you might use a factory class to grab request data and create an object:

class poly_base_Factory {
    public static function getWriter() {
        // grab request variable
        $format = $_REQUEST['format'];
        // construct our class name and check its existence
        $class = 'poly_writer_' . $format . 'Writer';
        if(class_exists($class)) {
            // return a new Writer object
            return new $class();
        }
        // otherwise we fail
        throw new Exception('Unsupported format');
    }
}

Like I said, there are many other strategies to use depending on your requirements. In this example, a request variable chooses which format to use. It constructs a class name from the request variable, checks if it exists, then returns a new Writer object. If none exists under that name, an exception is thrown to let client code figure out what to do.


Step 5: Put It All Together

With everything in place, here is how our client code would put it all together:

$article = new poly_base_Article('Polymorphism', 'Steve', time(), 0);

try {
    $writer = poly_base_Factory::getWriter();
}
catch (Exception $e) {
    $writer = new poly_writer_XMLWriter();
}

echo $article->write($writer);

First we created an example Article object to work with. Then we try to get a Writer object from the Factory, falling back to a default (XMLWriter) if an exception is thrown. Finally, we pass the Writer object to our Article’s write() method, printing the result.


Conclusion

In this tutorial, I’ve provided you with an introduction to polymorphism and an explanation of interfaces in PHP. I hope you realize that I’ve only shown you one potential use case for polymorphism. There are many, many more applications. Polymorphism is an elegant way to escape from ugly conditional statements in your OOP code. It follows the principle of keeping your components separate, and is an integral part of many design patterns. If you have any questions, don’t hesitate to ask in the comments!

CodeIgniter from Scratch: Displaying & Sorting Tabular Data































In today’s video tutorial, we are going to use CodeIgniter to pull information from a database and display it in a sortable table structure. This is a quite common task, especially inside admin areas, for displaying database records. We’ll be utilizing a few different utilities, such as the active records library and pagination.


Catch Up


Day 16: Displaying & Sorting Tabular Data

Day 16: Displaying & Sorting Tabular Data

Thanks for watching! Any questions/thoughts?