COMPANY ABOUT

FaceySpacey was born in the hay-day of both MySpace and Facebook--when both were the pinnacle of social networking. That’s where we get our name. Though Facebook has become the one to rule them all and MySpace is long gone, FaceySpacey remains the development shop you’re looking for with the years of social networking experience it takes to turn that twinkle of an idea in your head into software application innovations. In other words, we build startups soup to nuts for our clients, and help them become successful.

What we represent is something very special: we take dreams (typically software applications), turn them into rocket ships, supply all the parts you’re not sure you need yet, piece them together into a cohesive application via methodologies we’ve spent years honing, and help you take it to the stars for other to see and become a part of.

To learn more about us, we invite you to an overview of our process. We believe there are 4 core ingredients any startup needs to succeed. Click the links below to learn our process for each them:

-speccing

-branding

-coding

-marketing

WELCOME TO FACEYSPACEY

SPECCING

There are several schools of thought when it comes to how much you pre-plan your application and how much your developers develop it with agility, i.e. according to so-called “agile” practices. Our take is that “Agile” has been misinterpreted by many a failed startup as an excuse to operate without a proper plan.

However it goes deeper than that: we believe there are different best practices depending on the scenario. If you’re a funded startup (i.e. with funding in the millions), you have the luxury of refining an iterative process where you explore what you want to develop in small steps. For new startups, this is a costly phase where you figure out your development process. So if you only have $50k-150k for your project, you’re in a completely different boat, and you simply cannot afford that. You have to operate completely differently. We believe it boils down to 1 thing you absolutely must do differently: completely plan what you will get for your $50-150k. This means you means you must know exactly what you plan to launch to the public in your initial offering. And this requires a greater degree of what has been often, and pejoratively, called “crystal ball” planning. This is where we excel.

This is how we do it:

-SCOPE OPTIMIZATION: we keep the scope small, but quite a bit larger than what you’d get with one iteration which ultimately wouldn’t be what you feel is suitable to launch to the public--ideally down to what a multi-million dollar startup might accomplish in about 10 small iterations/sprints. In short, we determine the concise set of features that capture the essence of how you want to present to the public, and make sure not to waste any energy resources going farther than absolutely necessary.

-LAYOUTS: we produce layouts (and full designs in combination with a simultaneously running branding phase) of every page of your application, and every state each page can be in. the imagining of these layouts is what we do best. It’s where we explore deep into what you’re app could and should be. Other shops have to build lots of potentially useless stuff in order to see how far into the future we can, and not to mention waste lots of money during this exploration and process refinement phase. With FaceySpacey you can look at your entire application before a single line of code is coded, and know exactly what you’re going to get.

-WRITTEN ORGANIZED SPECS: this is simple once the layouts are produced. On a per page basis (and per state basis), we create written specs closely attached to the layouts, and organize these feature requests in FogBugz, Joel Spolsky’s project management software. Again, the key here is that the list of tasks are coupled to their layouts, and then that FogBugz is arranged in a way to mirror this association. Other shops may do more of a Bottom Up approach, where specs are written in association with the underlying data structures. We find the problem with that approach in $50-150k contract projects is that you, our client, can’t closely associate the tasks being executed to precise features you’re looking to see. For example, a database structure may be prepared and it took the developers a week to do, but you, as an end user testing the system, will have no way to associate the completed tasks to completed features you can use, and then you have no idea what you’re developers were doing during that time. In other words, we’ve optimized our process so at all times you know what’s going on in the form of testable features.

-DATABASE & APPLICATION DESIGN: First off, by “design” we’re referring to the planning of the underlying architecture. Just because we focus on a Top Down approach, where the specs and “product” lead the way, does not mean we also--simultaneously--take a Bottom Up approach. The difference is that before each decision we make for the underlying architecture, we have a precise product goal in mind we’re working to achieve. So in this part of our speccing process, we’ll come up with the entire database design--that always happens. Then we’ll prepare empty code files for all the code we anticipate building. Lastly, we’ll pinpoint potentially problematic areas in the application, and discuss and write a plan for how we will address them when we get to them. This way the entire plan isn’t thrown off track when we find a major challenge deep in the app that changes the way tons of other stuff should have been coded, or even the way other features should have been. The key here is that we do the tech speccing in conjunction with the product speccing. We continue to refine the product spec all the way until the tech spec is done. The result at times may be that we slim back some features or slightly change them, but specifically in a way that maximizes the product goal in proportion to the time it takes to develop.

-RHYTHM & TESTING: Typically called “sprints,” we establish predictable rhythm of execution through which you know when to expect results. The type of applications we do (to start) are medium-small applications that capture the precise minimal viable product you need. Therefore, we can do our sprints in increments of week at a time, rather than larger increments common to desktop applications of yesteryear. This insures you feel the pace at which we’re going from the start, and everyone can gauge progress, and accordingly feel comfortable with the process every step of the way. Starting on Thursday until Monday morning, you in conjunction with our dedicated testers test the application. Teams without dedicated testers are wasting your money by having highly expensive engineers be solely responsible for testing, and waste your time by putting the responsibility completely on you, somebody just getting acquainted with our process. The final point here is we do not move to new features until the current features work perfectly. The reason is simple: fixing bugs later when coders are less familiar with the code at hand takes many times longer to fix than fixing it right when they first made it.

BRANDING

At FaceySpacey, branding could almost be considered part of the speccing phase. We put design first. We put the user interface your users will use first. Many development shops will produce so called “wire frames.” If you’re familiar with them, you probably are seeing in your head layouts with little black square lined boxes representing elements on a page, e.g. a rectangle in the top left for a video player, and more rectangles in a column down the right column representing related users or other users. What we’ve determined is that these “specs” will be completely different if you have the opportunity to design them. Something theoretically sound in black and white lined wireframes might be a completely boring idea once designed. We allow the specs to change entirely throughout the speccing phase--because we do the branding phase simultaneously! The result is usually that we invent completely unique and innovative interfaces never before seen. A simple form with a bunch of fields stacked vertically on top of each other may become a several step process where you swipe from one field to the next on a tablet (or click a next button on a desktop). That’s a simple example, but should help you understand why the design and branding can completely change the specs for the product. Often you may end up with totally different (and better features). Another point we’d like to describe is the way address this combined speccing/branding: we borrow many aspects from other sites. We use other sites as overall branding influences. And more specifically we’ll copy/paste entire components from other sites--and then of course re-design it in our own style. The point is we maximize efficiency by not pretending that most of what we know is learned from other sources, though it may become second nature that we’ve forgotten where we got an idea from. So that means we cut the BS and say to ourselves: “we’re going to have comment wall widget exactly like Facebook’s.” Though we may end up making some tweaks to it, the point is we don’t waste any time pretending like we have to imagine such components from scratch. And we’ll share with you precisely where each component is influenced from, and thereby engage you in the process in picking and choosing already-existing components already out there on successful web & mobile applications. In short, we don’t think we have to make a Miles Davis or John Coltrane album to innovate where it counts. We believe the goal is to focus on what is unique about your application, and for everything else find efficiency in what has already been done, and do so very directly through a copy/paste process. But don’t worry, our designers will soup it up and make it your own in the end. Finding precise influences at the component level is one of our key ingredients to success.

However, the overall branding is slightly different than the many individual components that make up your site. For the overall branding, we’ll pick 3-5 other applications, and very closely mimic their best textures, placement of navigation/logos, etc. We reach a stage where it looks fantastic, but a little too close to the design of other apps. Then from there we make it our goal to make it your own, and completely unique. The result is that there is no designer taking stabs in the dark secretly throwing in whatever influences are ruminating in his head. We go through tens and even hundreds of influences, and share with you exactly what possibilities we think work best. And that means you’re not sitting waiting for a designer to come up with who knows what over a few days. Instead over a few hours, we’ve pin-pointed tons of apps we should borrow from. This is something other shops may want to pretend doesn’t happen or something like that. But we believe that by confronting this important aspect of learning from the greats that came before us, we can find great efficiency and keep you in the loop and contributing the entire time.

CODING

        The coding phase is the phase you, as one of our clients, can’t wait to start. It’s also potentially the most costly phase--because of the cost of multiple professional software developers we put on your project. The high cost of professional development is a fact other firms like to deny. FaceySpacey, on the other hand, brings this fact to plain view and confronts it with you in order to actually accomplish the best you can get for your money. We covered how we do this in our articles about the speccing and branding phases. The idea is that in those phases costs are cheap because you’re usually dealing with only me, James Gillmore, as your speccing guru, and Holly Welch, our Branding & Design director. So other firms deny this fact because their developers usually do not have the experience for what you want to develop, certainly have never executed something as large as your project before, and management just wants to get your contract. So management at these firms sell you as though they have the experience, which they don’t, and pay the lower costs of under-experienced coders.

You may ask: “Why does this happen so often?” The reason is extremely simple and rational: you would like to build a money-making invention. If they could truly do it on their own, they would, rather than work for a few upfront bucks. They would find a way to do it, even if they have to pay their bills. The developers good enough would not be working for these contract companies, and would rather be doing it themselves, or be a team member of a funded startup. Point blank, period. The ones that are good enough leave, and you’re left with the crumby or inexperienced ones that are learning on your project.

Yes, there are exceptions, and we’re one of them. Here are some of the exceptions you want to look out for while picking your team:

1) an extremely expensive company with fortune 500 clients. If you can afford them, get off our website now and go hire them. Objectively speaking and in favor of your standpoint, there’s just no reason to risk going anywhere else.

2) teams that are about go pro and do their own project, and leave contract development completely in their past. If you can be their last project before they go pro, this is who you would like to hire.

3) teams that know their place and do a small number of things really really well, and refuse to do many things not in their core expertise.

We’re #3. So what this means is we’re only really interested in developing a few types of startups these days. We of course do easy company and content sites, since we’ve managed to truly turn the process of shipping those product into an assembly line. But that doesn’t count. When it comes to startups we specifically are looking to execute products that fit within the following constraints:

1) web applications. not native mobile apps (e.g. on the Android or iOS platforms).

2) applications focused around 1 or 2 user types, and no more.

3) applications focused around one key content entity that your users contribute, e.g: a video, a checkin, a service offered, an apartment to stay in (i.e. as in AirBnB.com). So imagine the users creating a profile page for these entities, e.g. for your apartment, where most the interaction happens.

4) marketplace applications where users communicate and perhaps make a transaction over the primary entity type, i.e. again as in AirBnB.com. In other words, apps we develop usually mean your users’ actions revolve around that primary entity. And the key here is we won’t take on your project if in the first phase, you imagine more than one such entity. In our opinion, that would violate the “Keep it Simple Stupid” (KISS) development axiom we adhere to. That’s what causes projects to never get completed. We require your application to do one thing and do it extremely well.

5) applications with amazing user interfaces and user experiences in the web browser. We excel at javascript/ajax ;), and we love making tablet sites feel like native apps.

So that brings us to our coding process and what we bring to the table to make it so we can provide the stellar user experience and user interface your social networking marketplace application needs to survive in a modern web world where raw functionality simply doesn’t cut the mustard anymore.

Here’s the scoop:

        Applications we ultimately take on to develop end up having very common database and code architectures. That means server side coding will end up following a formula very closed to something else we’ve done before. Otherwise, we won’t do it. We have tons of ready-made and practiced solutions from similar past projects. We have tons of past FaceySpacey solutions we can learn from if not completely re-use, and these solutions are built on top of the Yii PHP framework. We like to think we’ve enhanced the Yii framework, and built a sub-set of tools specifically designed for these social networking marketplace style applications.

The net result is we can focus on the Javascript UI/UE, e.g. things like animations/transitions between states in the web browser that don’t require new page loads, rather than sites with a traditional page refresh browsing style.

Now the real important thing about this fact is that it gives you a front seat to the progress being made on your project. When projects require lots of server side work, and architectural work, you as the client are often left in the dark, being told lots of things are being done for your project, but with very little proof of the results. This in part is what has led to this focus at FaceySpacey. We like to please our clients and deliver gratifying results as often as possible--at least on a daily basis, and occasionally with hourly updates. Also, it’s just fun for us to making amazing user interfaces. It’s what we enjoy. And lastly, it’s the key ingredient to compete in this competitive world of Techcrunch startups. Sure there are data-heavy startups, but that’s not what we do. We know our place, and we do what we do well. We’re a user interface and experience company for web applications that get the product right.

So if you’ve read about our speccing and branding process, you know we work in one week sprints, testing with professional testers at the end of the week, while delivering you a release at that time as well. We use project management software where you can track as features are being developed. Generally, we make it top priority to share with you whatever is going on, most importantly through quick turnarounds. We select our projects wisely, and turn down projects that don’t match up with the constraints listed above. We have long term relationships with the developers assigned to your projects, and opt for a few awesome developers to work on your project rather than lots of mediocre ones. I, James Gillmore, personally layout the solutions/tools we use by picking and choosing from past projects, which will ultimately be similar in key technical ways to your project if we choose to take it. And lastly, we limit the technologies we use to just the following:

1) PHP

2) The Yii Framework

3) Javascript

4) jQuery

5) Ubuntu Linux

6) MYSQL

7) Amazon Web Services (EC2, S3, SQS, RDS, CloudFront, Elastic Load Balancer, etc)

And that’s us. If you’re somewhat technical, you can label us as a Yii/jQuery shop, with a hardcore product and user experience bent. Where we’ll exceed your expectations is in how innovative our product plan is and how easy it makes development. So what that really means is that the most important thing to note here about CODING is that our developers show up on time consistently. The reason this is so important is because great developers--more than many other professionals--require their own self-determinism and opportunity to contribute their own solutions to problems which they can be proud of. They do not want to be treated like a robot. Great developers simply won’t stand for it and will leave.

In short, our developers are our greatest asset, and we succeed because we hire people that get things done, and provide them with an atmosphere where they can show us and you how smart they are. Lastly, we pick great developers not because we know where to look. That’s easy to find out, but because they want to come work with us because they know we’re the best firm when it comes to Yii and jQuery. period.

MARKETING

        Ever heard of “the Marketing Mix”? I.e. the 4ps? Price, Promotion, Place (aka distribution), and Product. Those are the famous 4 ingredients to a good marketing plan. While we will also help you concoct a promotion and distribution plan, the aspect of marketing we focus on is the Product. In other words, all the speccing/branding we do (mainly the speccing) leads to a product the market wants, and eople will eat up. That’s really the secret sauce and magic of what we do. We will not let a product go through our doors and come out the other side that is not imagined/invented to disrupt the market and serve an under-served need. In other words, we invent products that sell themselves. We do cook up post-launch marketing plans, help with PR initiatives to get key blog posts on sites like Techcrunch and Mashable, etc, but as you will have read in our Coding article, we only focus on a few things and do those extremely well. In this case, we focus on building products that are so good they lead to viral word of mouth marketing.

That said, we also focus on building viral channels into your application, i.e. automated means of sharing. Here are a few examples:

-Mailchimp newsletter signups

-Facebook signups/logins, and facebook posting. Twitter & Foursquare too.

-SMS txt message invites/sharing

-Packaging content to be shared in visually appealing and captivating units

-Embedable/shareable widgets

-Proper email communication in accordance with on-site user-to-user correspondence to bring users back to the site

-APIs, i.e. we build your site an API for other developers to build their own applications on top of your application, which in turn brings more users to your app

-etc

In short, we make sure each user action leads to a unit of content or communication being distributed to the various major social networks and/or to specific users on and off the site in order to lead to more engagement. We take this goal very seriously every step of the way as we spec and plan your product.

And for those interested, here are some of the more traditional marketing endeavors we’ve done for our clients post-launch:

1) SEO, i.e. link-building. And of course pages on your application are all dynamically made to be on point in terms of on-site SEO

2) PR/Blog-marketing, i.e. reaching out to blogs to cover your application

3) Paid Search Advertising and Banner Advertising management

4) Email marketing, and campaign management

5) Brokering partnerships and content deals

6) Seeking additional rounds of investment. This can be a very important part of marketing for you post launch as well, since we’ll introduce you to a network of high profile Web 2.0 investors/professionals who will often blog/tweet about you and/or tell other people that will.

TUTORIALS INTRODUCTION

So you want to learn to program? Or perhaps you’re reading this because you’re currently a non-technical product guy, or guy with the next big startup idea, and you’re curious of just what it might take to become a coder. Either way, my advice is simply this: do not attempt to spearhead these “techcrunch startups” (previously called “Web 2.0 startups”) unless you’re a coder. Most startups that get funding from professional silicon valley investors are founded by developers. The ones that aren’t are founded by high profile product guys are management from big famous tech companies like Google, etc. So if that’s not you, and you want the best shot at making a successful startup, become a coder--that, or hire us ;).

Ok, so you’ve decided to continue reading this article and possibly give this coding thing a shot. The first thing to know, which should give you a serious confidence boost, is that learning to code is easier and takes less time than all the hours you put into learning math in school. Therefore if you were able to even just get through algebra, you can do this--if you really want it, and can put in even a fraction of the time. Think about it: you spent hundreds of hours, if not 1 or 2 thousand hours in math class or doing math homework. There’s a lot more concepts to grasp in those math classes than there is necessary to become a php and javascript web development.

I’m going to break it down simply into some core high level concepts that should give you insight into what you’re life as a programmer might look like. I found that when learning to code the hardest part was that most books and tutorials about the subject were written by guys with knowledge too deep that they forgot what it was like to be first tackling this subject, and what questions you might have. Therefore, I’ve made it my goal to offer you the analogies necessary to start thinking like a coder.

The first thing I’m going to share is this: have you ever seen those black windows on the screens of coders, aka the “command line,” aka “the terminal,” aka “the shell,” etc? Those are simply ways to control a remote computer via commands, rather than a graphic user interface (GUI). In short, you’re basically in side your server in a data center somewhere, doing things like installing Microsoft Word, or in the case of a web server, installing applications such as PHP, Mysql, etc. These tools are simply applications that are installed similar to applications with fancy GUIs that you see on your desktop computer. It took me a while to grasp this, but the idea is simply that these applications instead of functioning to show you pretty interfaces of a video you’re editing, or letter you’re writing, function to interpret plain text input and produce an output of more plain text. For example, if you wrote PHP code like this: if(true) { echo ‘yes’; }, and then offered that as input to the PHP application installed on your server, the PHP application would interpret (aka “parse”) that code and return output containing the word “yes”. And typically, that output would be sent straight to the web browser.

Now we have 2 new questions: 1) when would the web browser display this result? and 2) what is this about “input” and “output”? .

1) The web browser displays this result when you go to a URL such as this: www.yoursite.com/abc-folder/php-script-name.php . Basically you’re pinging your a server connected to the domain name “yoursite.com” and requesting a file named “php-script-name.php” in the “abc-folder” directory which is located on your web server just as files are located on your hard drive. The only difference is that in this case, the script will execute the above code, and return “yes” over the internet to your web browser. Exactly how your server knows how to get this response to you is not important now. What’s important is to understand simply that if you open the script “php-script-name.php” from a web browser across the world from the server that contains this script, the script will return “yes”, provided that you provide no input.

2) Now imagine that you entered this in your address bar: www.yoursite.com/abc-folder/php-script-name.php?something=dog. And imagine the script was re-written like this: if($_REQUEST[‘something’] == ‘dog’) { echo ‘yes’; } else { echo ‘no’; }, what do you think would happen? Well, provided that you passed some input appended to the script name, specifically “?something=dog”, you would get the answer “yes” and otherwise you’d get the answer “no”. That’s just one way to provide input to a script. The reality is that within a script there is a long chain of input and output between different blocks of code. It’s the job of the code to do different things by analyzing this output and making different decisions. You could display the word “yes” in red if the viewing user is a female and in “blue” if the viewing user is a male for example. You could then make “no” green in a red based on the sex, thereby combining 2 pieces of info (whether “dog” was supplied as input and the sex of the user) to produce different output. The principle is still the same, coding is all about input and output, i.e. taking various input provided by the user (which can be many many things, and from many many places, possibly from previously stored data in the database or in cookies), and producing different output.

If you understand these 2 concepts, the next thing to do is to learn some basic HTML in this article. HTML is easy. If you care to put any time into learning how to code web applications, you’ll figure it out easily. The reason it’s so important to learn is because PHP coding is all about generating HTML. By “generating” I mean what experienced coders describe as “dynamic” without thinking.

But “dynamic” and “dynamically” are terms that at first can be quite foreign to non-coders. What they mean is potential to change. An HTML web page dynamically generated by a php script may look a certain way one day, and a different way the next. Simply imagine the date changing from day to day on a web page. HTML isn’t capable of knowing the date. However a PHP script can, and thus can dynamically adjust the HTML spit out to your web browser as output.

That’s a basic example, but where this is all going is the concept that many different aspects of a web page can dynamically change according to the php calculations made on the server. The result is generated web pages from templates that look slightly different. And I hope I’m not dropping another loaded term with “template,” but I think “template” is a good term to end on.

The idea is that the goal of using PHP in combination with HTML is to allow parts of the page (i.e. HTML snippets) to change according to PHP logic, while other HTML snippets stay unchanged. The term for the unchanged HTML snippets is “static,” i.e. unchanging. That’s the difference between dynamic and static. HTML without the aid of tools like PHP is static, unchanging, and with the help of PHP can become dynamic, changing. The logic that determines how your web pages change will be up to the product goals of your application.

Now that you have an idea of the differing responsibilities between PHP and HTML, it’s up to you to decide if you want to skip to learn some PHP and the basic logic it’s all about, or if you’d like to understand more about how web browsers interpret HTML to determine the presentation/display/design of web pages. We recommend that latter because the basics are really easy. You don’t need to master it, but it will help give you an end game to think about while you’re learning PHP, since HTML is the output your PHP code will be generating 99% of the time.

HTML | PHP

PHP 1 - Dynamic Code Paths & Variables

        This tutorial on PHP should be treated as a tutorial about learning the basics of all programming. It’s goal is to be an eye-opener into what programming is about.

The reason we think PHP is the language to start learning programming through for the web developers is two-fold:

1) it’s syntatically similar to Javascript, which all web developers will have to learn, since it’s the language of the browser (note: HTML works in conjunction with javascript in the browser, where HTML deals with simple display & presentation, while javascript does the heavy lifting necessary for animations, and ajax calls to your server that don’t require a page refresh). PHP is also syntactically similar to C/C++ which is basically the grandfather of all modern procedural & object oriented programming.

2) it’s the easiest language to setup on a server and get productive with, as it’s the most prevalent web development server side language. That also means it has the most resources to learn it and all its tools.

So back to the tutorial. I like to start be introducing if/else statements since it does a very good job at highlighting how programming is really all about basic logic you already know. Code example time:

$variable = 2;

if ($variable == 2) {

    echo ‘the variable equals 2’;

}

else {

   echo ‘this code path will not get executed currently’;

}

So that code if executed will always echo out “the variable equals 2” to the browser. That’s fine. Quick note: a variable in PHP is any word that stands with a $ symbol. Simply a variable is a placeholder that at different times can hold different values. If you don’t fully understand variables yet, just look out for any $words like that--you’ll understand soon. So lets break down a few important things going on here:

1) THE FOLLOWING IS THE ASSIGNMENT OF THE VALUE 2 TO A VARIABLE CALLED $VARIABLE:

$variable = 2;

2) THE FOLLOWING TESTS WHETHER $VARIABLE EQUALS 2 (THE DOUBLE EUQAL SYMBOLS HERE IS THE DIFFERENCE BETWEEN THIS COMPARISON AND THE ASSIGNMENT IN #1 ABOVE):

if ($variable == 2)

3) THE FOLLOWING CODE BETWEEN THE BRACKETS DELINEATES 2 SEPARATE CODE PATHS. THE CODE WITHIN THE BRACKETS IS OBVIOUSLY WHAT GETS EXECUTED DEPENDING ON WHICH PATH IS TAKEN. WHAT PATH IS TAKEN IN THIS EXAMPLE IS THE FIRST PATH SINCE THE COMPARISON RESOLVES TO TRUE. OTHERWISE THE “ELSE” PATH WOULD BE TAKEN:

...{

    echo ‘the variable equals 2’;

}

else {

   echo ‘this code path will not get executed currently’;

}

So let’s make this a bit more “dynamic,” which as you may recall means changing. Let’s try to make it so it’s possible for both of the 2 code paths to be taken:

$dayOfMonth = date('j');

if ($dayOfMonth  < 15 ) {

    echo ‘it’s the first half of the month’’;

}

else {

   echo ‘it’s the second half of the month’;

}

So clearly this will execute one code path the first half of the month and the second code the second half of the month. Don’t worry about date(‘j’) just yet. That’s obviously finding the day of the month. It’s called a function. We’ll get to it later in detail. They’re actually quite simple to grasp. Simply you provide it some input in the parentheses and it gives you a response, which in this case is assigned to the variable $dayOfMonth. Basically the date() function is connected to your server’s clock and knows the date and time, and in this case is returning the number for the current day of the month.

So to wrap up your first PHP and programming in general tutorial, i’d like to simply point out the most important thing that you learned: languages like PHP allow you to dynamically determine to different code paths, i.e. different results to display to the end user. That’s the main goal. That’s the main birds-eye-view concept to really get a hold of before moving on.

PHP 2 - Functions

So if you read the PHP 1 tutorial, you got a hint at what a function is. If you took algebra in school, you’ve already done a lot of work with functions. A function is all about input and output, which you learned about in the Introduction to Programming tutorial. So it allows you to provide some input, and depending on the input allows you to get returned a different output. In order to not introduce more things than necessary, let’s go back to the date() function.

As you may recall, we provided date() with the ‘j’ parameter like this: date(‘j’). In this example, ‘j’ is called a parameter, sometimes referred to as an argument. There is a slight difference between the terms “parameter” and “argument,” but for brevity let’s just stick with “parameter.” Basically in this example, the ‘j’ means to take the current date and return just the day of the month. If we supplied an ‘m’ like this date(‘m’), it would return the number for the day of the month. Simple as that. Different input led to different output being supplied.

The next thing to learn is that programming languages have built-in functions such as date() which as mentioned before is internally connected to the system clock of your server/computer. There are also user defined functions. To explain this we’re going to go back to the code example from the PHP 1 tutorial and turn it into a function like so:

function halveMonth($dayOfMonth)

{

if ($dayOfMonth  < 15 ) {

              return ‘it’s the first half of the month’’;

}

else         {

             return ‘it’s the second half of the month’;

}

}

$dom = date('j');

$theDayOfMonth = halveMonth($dom);

echo $theDayOfMonth;

So the first thing to notice is that we got the current day of the month outside of the function. Then we passed it as a parameter to the function. The function then took this input and instead of “echoing” the result to the browser, it returned the text string (i.e. “it’s the first half of the month”). And then it assigned it to the new variable $theDayOfMonth, which subsequently was echoed to the browser.

What this allowed us to do is make a piece of re-usable code in the form of this function. Now we can call halveMonth($variable) anywhere we want and not have to re-write all the corresponding if/else code. bingo. Functions allow you to tuck code away for reuse.

The last thing I’d like to point out is how we have 3 different variables that all hold similar data:

1) $dom (the variable passed as input to the function)

2) $dayOfMonth (the variable the function deals with)

3) $theDayOfMonth (the variable the output of the function is assigned to)

The names basically all could have been the same, but I made them different so you could simply see that we were dealing with separate areas of the example. What this boils down to is a term called “scope.” Variables in the definition of the function (i.e. the code block that started with “function halveMonth($dayOfMonth)”) only pertain to that code block where the function is defined. Think about it like this: code within the function definition is very separate from code outside the function. By outside the function, i mean this code here:

$dom = date('j');

$theDayOfMonth = halveMonth($dom);

echo $theDayOfMonth;

That typically would be called “client code” in terms of its relationship to halveMonth(). Just like in business a client hires a contractor to serve up some results, here the “client code” hires halveMonth() to serve up some results. So here in the world of the “client code” the variables are all in the same “scope.” That means if we re-wrote the above code like this:

$dom = date('j');

$dom = halveMonth($dom);

echo $dom;

$dom will go from having an assigned value of something like “15” to having an assigned value of ‘it’s the second half of the month’. In other words, we overwrote the value of that variable. If you needed to keep the original numerical value and use the output text string at the same time, you’d use 2 different variables like I originally had. Either way, the point is that here outside the function, variables of the same name will overwrite each other when assigned new values. This is called “scope.” Continue to PHP 3 - Scope to learn more.

PHP 3 - SCOPE

If we re-wrote the function definition (from PHP 2 - Functions) like this:

function halveMonth($dom)

{

if ($dom  < 15 ) {...

nothing would change. The name of the variables within the function is totally unrelated from the names outside the function, and can be the same names or different names or whatever. They are not related. THE POINT IS THIS: if for example in the function definition, we re-assigned the value of $dom, that would not change the value of $dom outside the function (unless of course the returned output was re-assigned to $dom). So that means this (let’s go back to the original code snippet and modify it a bit to use $dom inside and outside the function):

function halveMonth($dom)

{

            $dom = 17;

if ($dom  < 15 ) {

              return ‘it’s the first half of the month’’;

}

else         {

             return ‘it’s the second half of the month’;

}

}

$dom = date('j');

$theDayOfMonth = halveMonth($dom);

echo $theDayOfMonth;

will lead to $dom within the function definition having a value assigned of 17, and outside the function here $dom = date('j'); the value of dom would be 15 on the fifteenth of the month. So by assigning it 17 within the function definition, we’re not overwriting the value of $dom outside it in the “client code.” That illustrates the definition of “scope.”

If it’s not fully clear yet, it will become clear after a little more study. The important thing to implant in your head and think back to when attempting to grasp this in the future is that scope means variables at different levels of the code can have the same names and are not the same variable and not related at all--though similar names can be used to help programmers reading the code figure out what’s going on.

PHP 4 - HOW TO LEARN PROGRAMMING

If you read PHP 3 - SCOPE you may have noticed i left you with what might seem like a vague description of scope. Accordingly I would like to point out something very important about how I’m writing these tutorials: my main goal in writing these tutorials is to come at an angle of teaching (and learning) that is very different from everything else out there. Specifically, my goal is to teach you the techniques I’ve learned that help me learn better. So in other words, my goal is not just to teach you programming, but to teach you how to learn programming (and how to learn in general). That will help you learn programming way faster. That said, what I wrote in PHP 2 - FUNCTIONS about “implant in your head...” is a very important technique I have while learning a subject.

Basically the technique goes like this: if there’s a concept I don’t fully understand, but I know is central to learning the subject matter, I file it away in my brain as something noteworthy that i’m inevitably going to have to understand, and look out for more lessons and explanations that will further explain it and help me grasp it.

The next bit about this is that I actually gave you what you should file away. Most of the time when reading these tutorials on the web or in books--though written by very capable of authors--they do not give you that nugget, or rather that seed which will grow. And often that means you’re left with an unconfident feeling. I find it better to give you something that will make you feel confident about the true baby steps necessary to grasp the subject matter. That’s what will lead to you not giving up, and the neurons in your brain forming the proper conclusions on your own, so next time you come back to the subject matter you’re stronger. It’s just like as if you’re working out and work out too hard and pull a muscle, and can’t come back for a long time to train again, but if you took the proper baby steps you’d be back at the gym the next day still growing your muscles.

So I’ll reiterate, here the seed that has a high likelihood of growing into a tree/muscle is:

“scope means variables at different levels of the code can have the same names and are not the same variable.”

Again, that’s not the complete definition, and it’s put in very layman’s terms, but should give you an idea of how different pockets of code are connected and how they’re not. In the case of functions, they’re specifically connected in 2 places:

1) on input via the parameter passed in between the parentheses halveMonth($parameter); 

2) and the output when the result is assigned through an equal sign back to a variable in the current client code scope:

$response = halveMonth($parameter);

PHP 5 - ARRAYS

So now we’re going to get into what I consider the most important thing in order to be productive with programming: loops & arrays. I remember when I was first learning programming, I basically got the concept of loops, but I really didn’t get their importance. I certainly didn’t understand precisely how important it would be. It wasn’t until I got to object oriented programming where I really fell in love with the value of loops and arrays, specifically when looping through objects of the same type, and performing similar actions on the objects. Talking about objects is a little bit too advanced for what I’m trying to convey right now. Just put it into the back of your mind that we will in a later tutorial deal specifically with looping through arrays of objects, and the results will be so extraordinarily useful, and appear in almost every web page you make.

Ok, so before we can get to loops you need to understand arrays. I’ve always wondered why every explanation I’ve read of what an array is didn’t start by describing the definition of an “array” in plain English unrelated to programming. Either way, that’s how I’ll start. Without even looking up the precise definition of “array” in a dictionary, I’m going to describe it in a way I think everyone thinks about it, and I’m going to do so with an example: you buy a box of Crayola crayons and dump them all out on a table, you now have an array of crayons to choose from. You have more than one or many crayons. The connotation I usually think of when thinking of “array” is a bunch of items, specifically where they’re all not the same.

In programming an array is a list of items. So simply we have a variable called $anything. The idea is that this variable holds a laundry list of items. So rather than $anything equaling 1, it equals a list of values, such as 7, 4, 8, 9, 10. That only leaves one final thing to understand, which is simply the syntax with which these values are stored under the heading of this single $anything variable. In order to demonstrate how multiple values are stored under a single heading, i.e. within a variable of a single name such as $anything, I’ll provide an example:

$anything[0] = 7;

$anything[1] = 4;

$anything[2] = 8;

$anything[3] = 9;

$anything[4] = 10;

So that means you can get the value of one of these items like this:

echo $anything[3];

The result is that 9 is displayed in the web browser. The number 3 in this case is called the “key” and 9 is the “value.” So basically you can access any values in the list by using the key. Just while we’re at it, I’ll point out that this array could have been built like this:

$anything[ ] = 7;

$anything[ ] = 4;

$anything[ ] = 8;

$anything[ ] = 9;

$anything[ ] = 10;

As a feature of the PHP language/application, it will automatically increment the keys when you build the array like that.

Final note about arrays: the keys can be text strings such as:

$anything[‘some_name’] = 5;

echo $anything[‘some_name’];

And I’m sure you know what that will do.

PHP 6 - LOOPS

So now a quick intro to loops. Firstly, keep in mind the list of values stored in the $anything array from the PHP 5 - ARRAY tutorial. We’ll start with some code:

foreach($anything as $k => $v) {

        echo ‘the key is ‘ . $k . ‘ and the value is ‘ . $v . ‘<br>’;

}

The result in the web browser will be:

the key is 0 and the value is 7

the key is 1 and the value is 4

the key is 2 and the value is 8

the key is 3 and the value is 9

the key is 4 and the value is 10

the key is something_name and the value is 5

Quick note: the periods around the variables above are how you separate text strings (“literal strings”) from variables, and the <br> string at the end is simply HTML that says put the text strings echoed out to the browser on new lines.

And most importantly, the language structure

foreach($anything as $k => $v) {...

simply says take the array and iterate through it, aka “walk through it,” aka loop through it, etc. And then simply in the block between the parentheses that follow, $k and $v will be the variables used to refer to the keys and values of the array. That’s it. That’s the most important thing you need to know about loops in PHP.

Another quite note: if your code went like this:

foreach($anything as $v) {...

then you have access to only the values in the parentheses. It’s an extremely common shorthand, used when you don’t need the values of the keys, which usually is the case when the keys are incrementing numbers from 0 up.

The next thing to understand is the for loop. In languages like C, there is no concept of a foreach loop. All there is a “for” loop, which is a lot less automated. It doesn’t have intelligence of the array it’s iterating through. In programming terms, they’d say foreach loops are “coupled” with the concept of arrays. That’s not the case with for loops.

for ($i = 1; $i <= 10; $i++) {

        echo $i  . ‘<br>’;

}

So what do you think that will do?

1

2

3

4

5

6

7

8

9

10

Take a second before I explain what’s going on to guess what it’s doing...It’s simply echoing out the value of the $i variable to the browser, which starts as 1, since $i=1 is the initial assignment of the $i variable as set before the first semicolon. It ends at 10, because the second statement before the second semicolon says to stop when $i reaches 10. And the 3rd statement says to increment by one after each loop. That’s it.

Now let’s imagine iterating through our previous array using a for loop:

for ($i = 0; $i <= 4; $i++) {

        echo $anything[$i]’;

}

That will simply alter the keys of the $anything array before echoing out the value for that key. It just so happens that the keys of the $anything array are ordered numbers from 0 to 4. If we tried to echo out the value of the $anything[5], nothing would be output since there is no value there. This loop would not be able to echo out the value of the ‘some_name’ key like the foreach loop would.

PHP 7 - CONCLUSION & MORE LEARNING TECHNIQUES

That concludes the basic PHP part of our tutorials. You have just had a birds-eye overview of what is called “procedural programming” in php. Later we’ll get to “object oriented programming” in php.

I’d like to point out one last thing regarding for vs. foreach loops, you’ll use foreach loops way more often in PHP than you will for loops. The learning technique I would apply now is again to tuck this away for later, but do so like this: keep a look out for a practical problem where a foreach loop won’t solve your needs, and when that happens, re-read about for loops, and see if they provide the solution; try to imagine a for loop at some point in the future providing you with the solution you need. Otherwise, keep it moving, and don’t waste much more mind on this.

That’s another learning technique I apply: weigh the importance of certain subjects and keep it moving. Often, you’ll get your answers in later things you learn, and you’ll inefficiently waste time and energy trying to force the understanding of something you may never need, or something that will inevitably become clearer when you learn other aspects. So be OK with not necessarily fully understanding something or being able to see it’s practical use.

Some people may say it’s important to understand one thing completely before moving to the next. Being to determined to learn something is very important. I agree, but with a big BUT. The but is that I usually re-read everything I study at least twice. So you’re going to be back here anyway. I’m viewing the real learning process in way more long-term approach, not just a wam bam thank you mam, “read it once and understood it completely,” which rarely happens.

Right now, if this is your first time through, you’re building a general understanding of the landscape your tackling. This is what they call the “general to specific” way of learning. What I’m trying to do here is get you through the entire landscape of programming as quickly as possible to give you a birds-eye-view. Most of the time people give up because the teacher focuses too hard on each step prematurely, and just the bore the hell out of the student, or confuse him/her because pieces/clues to aid the student are missing since they come from other aspects of the subject matter at hand.

The reason I’m doing this is because once you have that birds-eye-view framework, you can so much more easily dive deeper and learn the specifics. The reason this is true is because it allows you to see how things piece together. It allows you to see the practical application of things. It allows the neurons in your brain to start building a fuzzy somewhat distorted picture of the entire puzzle, but at least some sort of picture of how it all relates. That makes it so much easier to find and learn what you’re looking for later. That’s really the entire premise of my entire teaching/learning technique. Learn general to specific, and then dive into the sub-topics more. It gives you a sense of purpose when you decide to go back of your own volition and figure out a specific aspect of the whole subject matter. Your passion and enthusiasm--birthed from quickly getting an overview of the entire subject matter--make it so much easier for you to understand something. If you care to learn something you will. If you’re force-fed it (prematurely usually), you are more likely to be confused and waste your time.

The other approach is specific-after-specific. Here you’ll spend hours on one point when you’re not quite ready to learn it. With general-to-specific, easy to understand pieces of information from other areas of the top level subject matter will serve as clues to aid better understanding when you go back and dive into each specific sub-topic, and you’ll simply learn quicker. But don’t forget, the key ingredient is truly wanting to learn the subject-matter. Hopefully after getting a birds-eye-view of the entire subject, like I’m providing now, you’ll cultivate your own interest to learn more ;).

OBJECT ORIENTED PHP 1 - INTRO TO OBJECT ORIENTED PROGRAMMING IN PHP

We’re going to start by going directly to a code example that will highlight the power of object oriented programming. I wish I saw this as the first thing I learned when learning OOP. Usually books/tutorials on OOP explain all the theory and individual features of an OOP language, but you’re left having no clue on the magic you can do with it. Once you see and understand the magic, neurons in your brain will get to work figuring out what aspects of OOP you need to learn next to get productive, and it will quickly all make sense. Here we go:

$article1 = new Entry;

$article1->title = ‘The Bible’;

$article1->pageCount = 100;

$article2 = new Entry;

$article2->title = ‘OOP PHP Programming’;

$article2->pageCount = 200;

$articles = array(); //you haven’t seen this yet, but this is just the initial creation of an array.

$articles[ ] = $article1;

$articles[ ] = $article2;

foreach($articles as $article) {

        echo ‘The book, ‘ . $article->title . ‘ has ‘ . $article->pageCount . ‘ pages. <br>’;

}

When output to the browser from your web server, the result is:

The book, The Bible, has 100 pages.

The book, OOP PHP Programming has 200 pages.

Ok so what’s happening? The first thing I want to point out is that I used an array. I used an array to store multiple objects. The 2 objects were created with these lines:

$article1 = new Entry;

$article2 = new Entry;

I used an array to store 2 objects. Then I looped through the array, echoing values from the two objects. I was able to access the data stored in the object in identical ways, which is why the foreach loop worked. The idea is that the object is a package of structured data. It’s like a variable in that it starts with a $ symbol, i.e. $article1. However it contains more data, similar to how an array contains a list of data. Syntactically it’s different in that you access the sub-data like this: $article1->title;  . I.e. the “keys” are strings (never numbers) that come after -> .

Next the idea is that each of the 2 objects is generated from the same template, specifically with the “new Entry” statement. There’s a term you will hear non-stop as you dive deeper into OOP for this template--it’s called a “class.” For now just think of the Entry class as a template, from which we can generate similar objects. Elsewhere this template/class is defined, similar to how a function is defined. The main thing here is that each objects generated from this template/class all have the same “keys,” i.e. again the part that comes after ->. In objects, these “keys” are actually called “properties”--so that’s how we’ll refer to them from here on out, now that you get the correlation.

In this example, the “Entry” class has 2 properties: “title” and “pageCount”. And each object generated from this class/template can assign their own unique values to these properties. This allows for us to iterate through an array containing these 2 objects and request data from these 2 properties and know that something will be there. Imagine you had 10 objects stored in an array, and each object corresponded to a blog article, i.e. it carried with it all the content necessary to display a blog article. So it would have the title, body of the article, author name, list of tags, etc. That’s where the power lies. You can write very simple code that will extract data from a similar place in a list of many objects like we did here:

foreach($articles as $article) {

        echo ‘The book, ‘ . $article->title . ‘ has ‘ . $article->pageCount . ‘ pages. <br>’;

}

capiche. Because the data is structured in a similar format, we can be sure it will always be there.

Right now, you should be asking yourself what the fundamental differences are between arrays and objects. Both contain basically lists of data, right? Well, technically you could achieve similar results with arrays, but you’d have to individually define the keys of each array to be things like “title” and “pageCount”. With object oriented programming, you can define a class once like this:

class Entry

{

        public $title;

        public $pageCount;

}

You do that once, and you can create objects created from that template/class any time you want without writing the same code. Note: to more experienced OOP developers, don’t worry I’ll soon start referring to classes as templates--I just feel that correlation is extremely important to make for newbies, so I’ll keep combining the two with a slash for a little while longer before just calling them “classes” always.

So the key principle here is that each of these objects have the same “interface.” Interfaces are the key to good programming. If you’re new to this, which most of you are reading this, then the term “interface” is sure to get you thinking, curious, and possibly confused. My favorite analogy here is that of a Microwave. You know how it has all the buttons to control it, and the numbers 1-9 to determine how long you want your food to cook for, etc, right? And you can cook your meal with these buttons without having to know the internals of the microwave, i.e. you don’t have to know the slightest thing about how micro “waves” vibrate your food to cook it, etc. Well, that’s an interface. An interface provides a simple way to control something without having to know anything about its internals.

In object oriented programming, these object $variables are accessed by these interfaces, i.e. the properties “title” and “pageCount”. The takeaway here is that the interface is CONSISTENT!!! From object to object (generated from the Entry class), the interface is the same. And that’s what allows you to loop through objects (such as those in an array) and echo out the unique data within each object, but without having to code any different code to access each object. They are all accessed the same.

OBJECT ORIENTED PHP 2 - OBJECT METHODS (AKA FUNCTIONS)

Ok so if you get the bit about objects being similar to arrays in that they hold lists of data but are accessed through “properties” rather than “keys,” and you’re asking yourself: “that’s all?” then prepare yourself for the cool stuff. Here we go--lets lead with an example:

class Entry

{

        public $title;

        public $pageCount;

        public function getInfo()

        {

                echo ‘The book, ‘ . $this>title . ‘ has ‘ . $this>pageCount . ‘ pages. <br>’;

        }

}

Now let’s loop through those objects previously created in the PHP 8 tutorial:

foreach($articles as $article) {

        echo $article->getInfo();

}

The most important thing to notice--the practical goal accomplished here--is that in our “client code” we can echo the result of this code out to the browser:

echo ‘The book, ‘ . $this>title . ‘ has ‘ . $this>pageCount . ‘ pages. <br>’;

and do so without having to write that code. What I mean is that we wrote it one central place. If in another part of your web application, you need to echo this info again, well boom, just type echo $article->getInfo();. Capiche!

What has happened here is that we’ve given our object not just properties, but methods, and we did so with this line in the class code:

public function getInfo()

{

        echo ‘The book, ‘ . $this>title . ‘ has ‘ . $this>pageCount . ‘ pages. <br>’;

}

In essence, objects derived from the Entry class have a function called getInfo() . To understand the difference between methods and the functions you previously learned about, let’s compare this to regular functions like date() or halveMonth(). Notice those do not come after $objectVariableName-> . Basically those sort of functions are global functions, where as the getInfo() function (called “method” in this case) applies only to a given object. What makes it special is that it innately has access to the other data stored in the object, specifically the data stored in its properties.

Now this is where you’re likely to have trouble understanding what I’m about to teach, but let’s give it a try. Go back to the method definition in the class:

public function getInfo()

{

        echo ‘The book, ‘ . $this>title . ‘ has ‘ . $this>pageCount . ‘ pages. <br>’;

}

See the “this” in bold. That’s a special php feature to refer to the current object. Remember, this method exists within a class, and a class is a template. It’s not the real thing. It’s not a real object. It’s a blueprint of what a real object will look like. So it needs a way to refer to itself. Later in client code objects generated from this class (technically called “instantiated”) will not use “$this” but rather the $variable name you assigned the object too.

Really, the best way to understand this is straightup by testing these examples and making a few modifications yourself, i.e. actually doing a little coding. It’s extremely simple to do, but hard to first get in its abstract written form. When you see it in action, it will instantly make sense--or at least a lot quicker. My suggestion is to flip to the Setting up Your Server tutorial, and get your server working and executing php, and immediately try these out by copy/pasting the code into one file. Typically, if reading a book about this, you’d go on to read many many more chapters all about the theory of OOP and all its features. But that’s stupid. If you can truly grasp this, all the rest will be fluff that just adds few other cherries on top.

Here’s the complete code snippet to copy/paste and execute:

class Entry

{

        public $title;

        public $pageCount;

        public function getInfo()

        {

                echo ‘The book, ‘ . $this>title . ‘ has ‘ . $this>pageCount . ‘ pages. <br>’;

        }

}

$article1 = new Entry;

$article1->title = ‘The Bible’;

$article1->pageCount = 100;

$article2 = new Entry;

$article2->title = ‘OOP PHP Programming’;

$article2->pageCount = 200;

$articles = array(); //you haven’t seen this yet, but this is just the initial creation of an array.

$articles[ ] = $article1;

$articles[ ] = $article2;

foreach($articles as $article) {

        echo $article->getInfo();

}

I’m not going to get into the other features of OOP, because in reality what you just learned here taught you the features of OOP php you’ll be using 80% of the time. Coders reading this may be freaking out, but the reality is you need to get your startup executed asap. You need to cut the bullshit and get productive asap. So this approach is very practical. Understand this, then refer to my further reading section to get a list of other books you should read to acquire true mastery.

OBJECT ORIENTED PHP 3 - INHERITANCE IN OOP

And actually there is one last thing worth learning now about OOP. You can make new classes that inherit from another class. Check this code:

class BlogEntry extends Entry

{

        public function exageratePageCount()

        {

        echo $this->pageCount + 20;

        }

}

Now let’s rebuild $article 1, but from the BlogEntry class/template instead, and execute this new method:

$article1 = new BlogEntry;

$article1->title = ‘The Bible’;

$article1->pageCount = 100;

echo $article1->exageratePageCount();

Now the browser reads that it has 120 pages. The idea is so damn simple: objects instantiated/generated from the BlogEntry class have access to all the properties and methods from the parent class, Entry. Therefore you can write a reduced amount of code when you want to create similar classes. point blank period. Again, don’t worry too much about inheritance yet. It’s a feature you’ll use a lot, but a very simple one to code up and make use of. You’ll know when you need to use it to not have to write redundant code.

Super final note on OOP: visualize all this OOP stuff as simulating a world in programming. The idea is to make coding more human-like, more like the real world. I.e. classes can have children and parent classes, just like humans can have real children and real parents. Later on you’ll learn even more ways objects can work together, just as objects and organisms in the real world can. But I’m not covering that in this book. Look out for the terms “aggregation” and “composition”--they are techniques to make objects work together to create re-usable code and efficient solutions. For now inheritance is the code reuse technique we’ll leave you on. Don’t plan on abusing it ;).

Yii & FRAMEWORKS 1 - INTRO TO FRAMEWORKS

Typically now, you’d be introduced some raw MySQL. The reality is to get productive you can skip to using a framework that will “abstract” all the MySQL code you’d have to type. To get advanced, you’ll most definitely have to master SQL (“Standard Query Language”). But keep in mind we’re on the fast track to getting productive and getting the general-to-specific understanding of the entire scope of what you need to know...By the way “abstract” means in layman’s terms to make coding easier by creating a layer on top of deeper code that makes the most common tasks easier. So frameworks provide a precise toolset (i.e. set of code commands you can type) that handles the most common tasks you will need to execute without having to know all the internals. The result is you get to remember a lot less coding commands to accomplish major things.

The framework we recommend is Yii, which is the best PHP framework around right now as of August (2011). period. Don’t waste your time researching all the different PHP frameworks available. Just learn and master Yii: http://www.yiiframework.com .

So let’s start with an example so you can get an idea of the power of the Yii Framework to inspire you to continue your study of it. We’re going to create an Article class:

<?php

class Article extends CActiveRecord

{

        public function tableName()

           {

                return ‘article’;

           }

        public function getInfo()

        {

                echo ‘The book, ‘ . $this>title . ‘ has ‘ . $this>pageCount . ‘ pages. <br>’;

        }

}

Ok, so notice, we did not define the “title” and “pageCount” properties. The reason is because this Article class automatically grabs these properties from columns in your article table in the database. We’ll cover SQL later, but real quick: the idea is a database is a series of spreadsheets with column headers, rows with similar data, and cells that hold the data that correspond to the current column each are in. So the idea here is that Yii simplifies how your PHP code works with the database. It inherently knows the columns of the corresponding table, and provides them as properties for all Article objects that extend from the Article class.

How does this happen? Well, through inheritance. This Article class you created extends CActiveRecord, which is a class within the Yii Framework. That means you have access to all the pre-built tools it provides. That’s it. By the way the Article class is called a “model”--it’s the “M” in “MVC.” It automatically models database tables.

So it lets you do things like tack on the getInfo() method and not have to do anything else to start getting results.

That’s the end of this lesson. The takeaway is that you create your classes by extending from classes in the Yii framework, and a whole lot of work is automatically done for you. We’ll explain how to install Yii in another article, but the basic idea is you associate the application you’re working on with your installation of the Yii Framework, and now you can reference classes, methods, etc, from the library of code provided in the Yii Framework.

Yii & FRAMEWORKS 2 - CONTROLLERS

Ok, so check it, remember at the beginning of the PHP tutorials you learned how web browsers connect to servers by accessing a script file remotely, and then the server executes the result and serves up the result to your browser, right? Well, in Yii and most MVC Frameworks (“Model View Controller”) only one script is ever pinged. You’re not pinging yoursite.com/script1.php and then yoursite.com/script2.php and then yoursite.com/contact.php, etc. Yii is wired in conjunction with some help of your server (typically Apache, which we’ll cover later, and which ultimately won’t be a big deal in getting productive quick) to make it so all requests to your site go through the same script, called index.php. In the browser, your Apache server will hide index.php from all URLs so you can access your site at yoursite.com without having to access yoursite.com/index.php. Another example would be yoursite.com/about which also would send a request through index.php.

What happens then is that the internals of all the Yii library code route the request to the proper set of Yii code. So if /about is in the URL, Yii will send the request to a code class called “about” and that’s where you write your code. Basically Yii will interepret pretty urls that don’t end with “.php” and route the request based on the words in the complete URL to the appropriate code to execute. capiche.

Code snippet time:

<?php

class AboutController extends CController

{

        public function actionUs()

        {

                $aboutUsText = “Some stuff about how great your new startup is...”;

                $this->render(‘viewFile’, array(‘content’=>$aboutUsText));

        }

}

Now if you were to visit yoursite.com/about/us this code would be triggered. Why? Well obviously because the bolded word “Us” comes after the word “action.” Yii controllers (which as you can see extend from CController) are programmed so that any method that starts with the word “action” correspond to specific pages requested. So the idea is when your request starts with “/about” then the AboutController is called, and specifically within it if after “/about” is “/us” like this “/about/us”, it’s “action method” that ends in “Us” is executed.

Now, to get a page to render to the browser, you have to call the “render()” method of the current controller class, which as you remember will require using the “$this” keyword. Yii controllers have a method called “render” which is all about displaying a specific view file, in this case called “viewFile” which is bolded to point out its importance. That view file (which is a php code file) is then displayed in the browser. That’s it.

Lastly, the view file (which will be named somewhere as “viewFile.php”) will be passed a variable called $content with the value of $aboutUsText. So in the view file you can place the $content variable anywhere you want to display the paragraph about your startup. The view file will be a combination of HTML and PHP snippets of dynamic code interspersed within it.

Yii & FRAMEWORKS 3 - VIEWS

Let’s start by creating the bare minimum view necessary to show your About Us page:

<h1>About Us</h1>

<div>

        <?php echo $content; ?>

</div>

We’re actually going to jump to learning HTML in the next tutorial. So I won’t go too deep into explaining what <h1></h1> and <div></div> means. In general, they’re called tags, and pair sof 2 matching tags (the ending one starting with a backslash) are called “elements.”

The idea here is simply that we display the value of the $content variable (i.e. your paragraph about your startup) right there in the middle of the HTML.

You may be wondering why we don’t just write that paragraph in plain text/html right there, rather than go through all the work of defining php variables in the corresponding controller class and then passing it to this view. Well, the answer is one you’ll typically here while studying programming tutorials: this is an easy example that shows the core features you need to learn, and when you want to do more complex things (specifically dynamic things, where the value of $content can change) the utility of coding like this comes to light. Basically we could use the above HTML view file as a template for many similar pages, such as those in a blog, and display different blog article content via the variables, rather than code a different view file template for every single blog article.

Yii & FRAMEWORKS 4 - FILE STRUCTURE

Ok, so by now, you should be wondering how the controller class’s render() method knows where the “viewFile” view is. The answer is simple, Yii basically requires you to organize your code files in a structured set of folders. Specifically here’s what your Yii directory structure will look like:

>yoursite

>controllers

        >AboutController.php

>models

        >Article.php

>views

        >viewFile.php

That’s an oversimplification that those familiar with Yii may pin as incorrect, but again the point is to get the main high level concepts here, not master every precise specific. Learning it this way will make it 10 times easier to learn the specifics later. And yes, I’m going to keep repeating the technique of learning/teaching I propose throughout my FaceySpacey tutorials.

So basically the code you write in the AboutController.php class knows that when you want to render a view file named “viewFile” to render a file in the following file: /yoursite/views/viewFile.php.

They call this “convention over configuration,” which is basically a motto Yii attempts to adhere to in order to do things like keep the file structure similar from project to project--i.e. Yii projects all follow a similar file structure convention/style. In this case, this saves many lines of code where you have to define full file paths every time you want to reference another file of code.

Yii & FRAMEWORKS 5 - PUTTING IT ALL TOGETHER

So let’s wrap up the framework tutorial by doing something a little dynamic to highlight the power of a framework.

class ArticleController extends CController

{

        public function actionView()

        {

                $article = Article::model()->findByAttributes(array(‘title’=>$_REQUEST[‘name’]));

                $this->render(‘viewFile’, array(‘model’=>$article));

        }

}

So what could we possibly be doing here? We’re dynamically finding a specific article and rendering it to the view. The idea is this code is made to render 1 of many articles in your blog, not just the same about us paragraph. In technical terms, we’re finding an article in the database, and passing its corresponding object that Yii generates to the view.

The view file would look like this:

<h1><?php echo $model->title; ?></h1>

<div>

        <?php echo $model->body; ?>

</div>

The view file here is passed the entire $model object, rather than just a plain variable that holds a single variable (i.e. previously the about us paragraph). This object has properties for the article title and the body of its article.

So the next question you should ask yourself is: ok so how does the blog know which blog article to display? The answer is simple: through clues in the URL you provide.

In this case, the URL will be something like this:  yoursite.com/article/view/name/the-article-name.

Let’s break down this url:

/article = the controller to use

/view = the controller’s action to use

/name = the key in the “global” PHP array called $_REQUEST

/the-article-name = name of the article.

So basically PHP has a global array called $_REQUEST which stores values in the URL. In standard php, urls would be structured like this:

yoursite.com/article/view?name=the-article-name.

However, in order to provide more beautiful URLs the Yii framework is programmed to give you access to that same data by structuring your urls using standard file path notation, i.e. /name/the-article-name.

Then in the php code you can simply access $_REQUEST[‘name’] to get the value “the-article-name”;

Finally, this line:

Article::model()->findByAttributes(array(‘title’=>$_REQUEST[‘name’]));

loops up an article in the article database table that has the title stored in $_REQUEST[‘name’].

So this allows your blog site to have URLs leading to different articles like this:

yoursite.com/article/view/name/article-1.

yoursite.com/article/view/name/article-2 

yoursite.com/article/view/name/article-3.

Final note: you may be wondering why the title is hyphenated. In reality, your article table would have a column called “url” or “slug” which is basically the hyphenated version of the article title. You could also have URLs like this:

yoursite.com/article/view/id/1

yoursite.com/article/view/id/2

yoursite.com/article/view/id/3

And then your finder code would look up the article in the database by its unique ID number column like so:

Article::model()->findByPk(array(‘id=>$_REQUEST[‘id’]));

Note: the findByPk() method standards for Find by Primary Key, which usually is a numerical auto-incrementing unique ID #.

The crux of what’s going on here is that the provided information in the URL can be different. Therefore your application code needs to behave dynamically and know how to deal with different provided information. This is basically the cornerstone of dynamic programming. It’s what makes coding in languages like PHP so different than the static HTML language, which is just basic commands about the placement/style of elements on a web page. In short, the code you write needs to be able to deal with various possibilities and still produce a result. Your code is expecting different “input” so it can give you varied, aka “dynamic” output.

The true true cornerstone here is this variable $_REQUEST[‘name’], which can hold different values. It’s one of the many ways your application can receive varied input.

So, fueled with a database of articles (and their urls/slugs), you have a ton of data to run searches on via Yii’s various model finder methods, i.e. Article::model()->findByPk(). I’ll explain what’s going on in that exact bit of code in a second, but first I’d like to finish my point here: the point is that with all the data in your database you’re innately prepared to deal with all sorts of input, such as the article ID # provided in the requested URL. You can then basically make a comparison and see if any data in your database has a matching ID #, and get the corresponding database row. From there it’s simple: yii turns it into a model object, and you can access the various columns in that row.

So back to this line:

Article::model()->findByPk()

All that is there is a common yii code structure to look up articles in the article table by primary key. You have to start with Article::model()-> . Why it starts with that is beyond the scope of this article, but the basic point is that your Article class has these tools available to it, and because of its tableName() method which you previously saw that returns the text string “article”, knows to look for rows in the article table by their ID #. Yii has a great deal of tools to perform complex database lookups. This is the easiest example.

That concludes the introduction to frameworks set of tutorials. You’re now armed with a basic understanding of the goals that MVC frameworks accomplish. You should start imagining how your application will work to dynamically display different content based on varying input. Keep in mind there are other places users can provide input: cookies (i.e. data your site stores for a long period of time in your visitors’ web browser), data submitted via forms, etc. Cookies, forms, URLs are really the main 3. They may actually be the only 3. But that won’t stop you from building wonderful complex and innovative applications. That’s all you need. After this initial input, a whole signal flow process can ensue in your application where one bit of code functions as input to another block of code, and then that block of code’s output is the input to yet another block of code. For example, if the user’s user ID was stored in a cookie, with every request you could lookup in your user table within your database the row corresponding to the current visitor, and then put that visitor’s name on every page. So the idea is you originally had a user ID as input from a cookie, and that served as input to a database lookup in the User table, and then that output served as input to a function that combines the first and last name to create a complete name, which then was output to the browser. That’s a chain or flow of continuous input and ouput, and you can do as much as you want in that chain, and it can go on for as long as you want. The result will always be the same though: you pass the result as an HTML web page to the browser from your server.

MySQL 1 - INTRODUCTION TO DATABASES & SQL

Ok so SQL stands for “Standards Query Language.” It’s a language to get data from basically tables that resemble Excel spreadsheets. MySQL is a particular application that will exist on your server (like PHP) based on SQL, i.e. that uses the SQL language to query those tables.

100% of the applications that these tutorials are written for will use MySQL. The Yii Framework, which we love, requires an SQL database such as MySQL. All the “models” in Yii mirror mysql database tables. That said, we’re not going to focus on MySQL in terms of its use in Yii right now. We’re going to focus on SQL by itself, and the main things you do with this language.

Let’s dive into some code:

SELECT lastname,firstname FROM user WHERE id=3

So what could that simple code snippet possibly be doing? It’s selecting a row from the user table where the user id is 3. It’s specifically selecting only the first and last name columns. If we wanted to select all columns we would use the asterisk symbol like this (note: the asterisk in programming often means all):

SELECT * FROM user WHERE id=3

So that would bring other data in the row, such as the user id itself, email address, phone number, etc.

Now let’s insert a row:

INSERT INTO user  (firstname, lastname)

VALUES (‘James’, ‘Gillmore’)

That clearly is inserting my first and last name into their respective columns. SQL is supposed to read like plain english. I’m not even going to explain each part, as it should be obvious. The goal of this tutorial is just to get you familiar with the main goals of SQL, i.e. to select data, insert data, and update data. Let’s look at updating now:

UPDATE user

SET firstname='Jamie', phone='310-849-8939'

WHERE lastname='Gillmore'

That’s updating the row with my last name to have my common nick name, and my phone #.

So that should give you a very good idea of what SQL is for. It’s all about accessing your data. In reality, in programming the sort of applications these tutorials are for, databases will be the easiest part. Basically you’ll find yourself building spreadsheet like tables at the beginning of development of applications, and from then on out for the most part you’ll use your framework, i.e. Yii, to query it via PHP code. Of course there will be some times you have to use SQL directly, but by the time you get to that point, you’ll be a master and learning more about SQL will be easy. So if a developer you hire makes a big stink about database work he has to do, he’s basically stupid. And in reality, he’s talking about modeling your product in general, and if you have a good product spec, it should be very obvious how to model your database. A few decisions may need to be made, particularly in terms of preparing for the future, but if you’re new to this startup thing, don’t worry about the future. Make a good spec and get the product coded up. So in short, it will boil down to how good your product spec is, and how well your developer understands it. Give your application a user table, a table for its primary data type, such as an Article, perhaps a Category table, add the necessary columns to each table, and bang out your application. It’s no biggie because you shouldn’t be attempting to code something extremely complex while you’re learning and new at this.

To learn more SQL go w3schools (it’s where I learned most of the SQL syntax, and I still refer to it regularly):

http://www.w3schools.com/sql/default.asp

MYSQL 2 - MYSQL & PHP

This tutorial will describe how to get MySQL data into PHP at the most basic level. You will use built-in PHP functions designed specifically for talking to your MySQL application. When I was first learning this, the hard part for me to get was how MySQL and PHP connect to each other. The idea is simply that both are applications on your server, and one application can talk to the other. And PHP specifically made ways to talk to php, i.e. through functions.

$username="username";

$password="password";

$database="your_database";

mysql_connect(localhost,$username,$password);

@mysql_select_db($database) or die( "Unable to select database");

$query="SELECT * FROM user";

$result=mysql_query($query);

$num=mysql_numrows($result);

mysql_close();

$i=0;

while ($i < $num) {

$first=mysql_result($result,$i,"first");

$last=mysql_result($result,$i,"last");

echo "$first $last</b>";

$i++;

}

specifically So what this code is doing is:

1) logging into your MySQL application via the PHP mysql_connect() function.  2) then selecting the database to use via the mysql_select_db() function

3) and then executing a SELECT query to grab all users from the database via the mysql_query() function.

One thing to point out here is that the SELECT statement SELECT * FROM user is grabbing multiple rows, unlike what you saw in the last tutorial where we used a ‘WHERE’ statement to limit the result to one row. So accordingly we must loop through all the results and echo the first and last name of each user on their own lines.

We use the mysql_result() function to access part of the $result set via its row # stored in the $i variable. The while statement simply loops from 0 upwards until $i is not less than $num, which via the mysql_numrows() function equals the total of rows stored in the $result resource.

In short, the while statement loops through all the rows in the result set, assigning the first and last names to php variables, and then echoes out the full name to the browser.

The key thing to notice here as you progress to the next tutorial is that this is where the rubber meets the road between your PHP code and your MySQL code. Even if you do end up writing lots of SQL in your Yii applications, you won’t have to do all this tedious common coding with functions like mysql_result() etc. Yii will automate all that for you, so at most you just have to enter a slick a SQL statement, and at least you don’t type any SQL at all.

MYSQL 3 - MYSQL & Yii (PART 1)

Yii allows you to enter raw SQL in various ways. But more importantly Yii also allows you to write Yii PHP code in ways that resemble SQL without having to write any real SQL. First let’s cover how to execute SQL statements in Yii:

Yii::app()->db->createCommand("UPDATE article SET promoted=’yes’ WHERE id=7")->execute();

So here we’re creating an SQL command and executing it. The command specifically is setting an article to promoted where the article id # is 7.

We’re not going to go too deep into the theory and syntax used here because our goal is simply to point out how Yii automates/simplifies/abstracts what rudimentarily could take many lines of code as you saw in the previous tutorial. The basic idea is that Yii has global tools you can use all starting with “Yii::app()”. So in this case, we’re accessing Yii’s database tool with the keyword “db”. Then we use it’s createCommand() method to declare some SQL to use and then the execute() method to execute it.

Now let’s see how to select data from the database:

$rows = Yii::app()->db->createCommand("SELECT * FROM article”)->query();

Here we simply extracted all the rows from the article table, assigned them to the $rows variable (which is now an array containing those rows), and executed the statement in this case with a query() method instead of an execute() method.


So that’s how you can execute raw SQL statements in Yii. It’s worth pointing out what’s called “fluid syntax” which is being used here. Notice how the query() method is attached to the createCommand() method with “->” in between, and even notice how “->” is used 2 times before to connect back to the “db” tool and all the way back to “Yii::app()”. What’s happening here is very cool, and one of my favorite things I first got the hang of. Basically each method is a method of an object returned from the previous method. So the createCommand() method simply returns a “command” object, and it has a query() method. You can make these chains on and on if it makes sense.  

MYSQL 4 - MYSQL & Yii (PART 2)

Now we’re going to inspect simpler ways of finding and saving data that Yii models have built into them. Yii models fyi are based on the “Active Record” pattern. Look it up some time: http://en.wikipedia.org/wiki/Active_record_pattern . All you need to know for now is the reason that model classes extend from a class called CActiveRecord is because Yii uses concepts from the Active Record pattern to design how your models will work.

So anyway the CActiveRecord parent class is what gives your models methods like findByPk() and findByAttributes() that you’re now familiar with.  Let’s go back to an example similar to what you’ve seen before in previous tutorials:

$articles = Article::model()->findAllByAttributes(array(‘type’=>’published’));

So that code is obviously finder code to return a list of published articles. What’s going on here is that in placement of SQL code such as this “ SELECT * FROM article WHERE type = ‘published’ ” the findAllByAttributes() method is used. And of course that method takes as a parameter an array with data about what to search for. The idea is that this is native PHP coding, and no SQL is required. It will make coding a lot easier and save you a lot of time.

Now let’s get into saving newly created articles.

$article = new Article;

$article->title = ‘The FaceySpacey Programming Bible’;

$article->pageCount = 300;

$article->save();

See how natural that last line is. You can simply create an object, and call its save() method, rather than write this SQL to save it:

INSERT INTO article  (title, pagecount)

VALUES (‘The FaceySpacey Programming Bible’’, 300)

The Active Record tools of Yii allow you to think in terms of PHP code, and more specifically in terms of Yii code, rather than Yii code, PHP mysql functions, and Mysql. It allows you to not have to jump back and forth between different languages, and think in terms of just a few core method and the parameters you pass to them. Basically it means there’s a lot less to remember, and what you do have to remember is the most powerful stuff that offers the most flexibility. In reality, in terms of finder methods such as findAllByAttributes(), it will all be about the parameters you pass to it. And these parameters are usually the application-specific pieces of information that are easy to remember such as table column names since it’s your application, rather than tons of coding syntax.

SETUP 1 - SETTING UP LAMP & AMAZON WEB SERVICES

Many things in software development rely on winning recipes. This is one of them, and the one that kicks it all off--one that’s required if you have any hope of getting anywhere in PHP coding and getting your application production ready.Quick note: if you don’t already know the, the acronym, “LAMP,” stands for Linux, Apache, MySQL and PHP, i.e. the 4 applications necessary to run the sort of apps these tutorials are written for.

The goal is this: to install LAMP using the Ubuntu flavor of Linux on an Amazon EC2 server. This by the way is the official FaceySpacey recipe. Ubuntu Linux is what we live by, and quickly become the best Linux distribution, especially for newbies like you. Here’s the official Amazon EC2 Ubuntu setup guide:

https://help.ubuntu.com/community/EC2StartersGuide

On that page is links to the latest Amazon EC2 AMIs to install. If you don’t know what an AMI is, it’s basically a template that you generate your Amazon EC2 server from. As of August 2011, here’s the latest set of AMIs:

http://uec-images.ubuntu.com/releases/11.04/release/

On that page is a table. You will be clicking the link in the AMI column. Find the row that corresponds to the region closest to you that has a 32 bit architecture and a “root store” of “EBS.” Click the link in that row, and it will link to your Amazon account and begin the process of creating an EC2 instance based on that AMI/template.

If you haven’t signed up for Amazon AWS yet, do so here:

http://aws.amazon.com/

Lately, they’ve been making you signup for each service you will use. Signup for EC2 to begin with.

Ok, so back to creating your instance. Go through the steps, and choose the following options when presented with them:

After you’ve created your instance, go to the Security Groups link in the left column. Click the “default” security group which was assigned to your EC2 instance. Set the rules so HTTP traffic is allowed from all IP addresses, and allow SSH traffic from the ip address of your computer. Find your IP address here: http://whatismyipaddress.com/ .

The next thing you will do is set your server up so you can login to it without using the keys provided by the Amazon EC2 web interface. Though experts will not recommend accessing your server via “root access,” I’m going to teach you how to do it since if you’re new to this you’re most likely dependent on root access for much of what you do.

But let’s first login once with the keys provided by the EC2 web interface, since that’s the only way to initially get in. Click the “Instances” link in the left column. Then right-click your instance row and click “connect.” There will be a set of directions there to follow. Basically it boils down to executing a command (from Putty on windows), or the Terminal on Macs and linux, and making sure the private key you created when you first created your instance is associated with the connection command. One thing to note is that you will connect as the “ubuntu” user, rather than the root user. That’s how Ubuntu AMIs are setup.

Once you’re logged in as the Ubuntu user, setup the password for the root user with this command:

# sudo passwd root

After following the steps to change the root password the above command will lead to, navigate to /etc/ssh/sshd_config and uncomment this line: PasswordAuthentication yes

Then restart your SSH server with this command:

sudo /etc/init.d/ssh restart

Now you can connect to the server remotely via the root and the password you set. Do that, i.e. login via SSH from the terminal with with user “root” and the password you set.

Next, now that we’re basically in control of your fresh EC2/Ubuntu Linux server, it’s time to install the applications you will need. First you need to update your server so that it gets the latest patches and updates from the internet, i.e. like your Mac or Windows computer regularly--and automatically--updates itself. Run this command:

apt-get update

Now execute the following commands one after another. Wait for each to complete before doing the next one:

apt-get install lamp-server^

apt-get install curl libcurl3 libcurl3-dev php5-curl php5-mcrypt

apt-get install mercurial

apt-get install phpmyadmin

apt-get install chkconfig

apt-get install subversion

apt-get install unzip

apt-get install php-pear  

apt-get install php5-dev  

apt-get install apache2-dev

We installed a few tools we commend there such as “mercurial,” which is a version control application--we’ll talk about that stuff in other articles. Just know this is our recipe to get everything done efficiently all at once, and that’s why installing such apps are in this article.

Ok, so next go back to the EC2 web panel. Go to the “Elastic IPs” link in the left column. Click the “Allocate New Address” button and create a new IP address. Then right-click the row that appears corresponding to your new IP address, and choose the “Associate” option from the menu that appears, and associate the IP address with the EC2 instance you previously created.

Now copy/paste that IP address into your web browser and visit that URL. You should see a message saying that your server is setup. Next go back to the terminal where you’re connected to your server, and navigate to /var/www. In that directory will be a file called index.html. Rename it to index.php like this

# mv index.html index.php

Now in that file, replace all the code there with:

<?php

phpinfo();

?>

Now you should be able to revisit that IP address URL and see a bunch of info about your server in pretty blue tables. That’s all the information about your server, the settings, and what is installed on it. This also means that PHP is working on your server, as well as of course Apache, which is your “web server” application that works in conjunction with PHP to display web pages to remote web browsers trying to connect to your server.

What next? Basically from here, you will create your applications in directories such as /var/www/application-name . After that, you will need to point your domains from godaddy (or wherever your domain names are hosted) to your server, and then on your server, you will associate an incoming domain name with directory path such as the aforementioned /var/www/application-name. We’ll describe this in the next tutorial.

SETUP 2 - CONNECTING YOUR DOMAIN NAME TO YOUR APPLICATION DIRECTORY

Ok, so this is a turning point for all those that have never setup code to be accessed through the internet. The end goal is simply so you can access www.yoursite.com in a web browser and see the result of your code displayed in the web browser. The first time I executed this, it made me really happy, and you’ll be sure to have the same reaction.

The high level explanation of what’s happening is simply that you matchup a domain name with a directory on your server. You tell your server that any traffic coming for www.yoursite.com should connect to the code located at /var/www/yoursite.com.

Navigate to /etc/apache2/sites-available. Open up the file there called “default”. Also note that if you don’t have a tool like SCP on windows you’ll have to edit these files at the command line using an application that comes with Linux called “vim”. So for example to access that file would type the following:

# cd /etc/apache2/sites-available

# vim default

Vim is a text editor for use over SSH in the terminal. Google “Vim tutorial” to learn how to use it, as it’s out of the scope of this tutorial. It will be a little abnormal at first, but it won’t be hard to get the hang of.

Also, what I love about running Ubuntu Linux on my own desktop is that you can connect to servers and access their file system the same way you access your local file system. I highly recommend anyone serious about getting their startup going that they install Ubuntu on their home computer. It’s really not that difficult to install. Just go here and follow their directions: http://www.ubuntu.com/ . Once you have it installed, just go to Places > Connect to Server and then connect to your EC2 instance via your root ssh credentials. That’s one reason why I violate the security precautions of using the Amazon-provided SSH keys...The other thing you can do is open up files on your server in text editors and IDEs just as you would files on your own computer.

Anyway, you’ve gotten to the point where you can edit the text files on your server. You’re now going to setup some Apache configurations to make your site accessible from yoursite.com . Open up that “default” file and add the following configuration lines to the bottom of the file (these are the bare minimum you need--there’s a lot more you can do to configure it, but to convey the main concept here, we’ll only show the minimum):

<VirtualHost *:80>

        ServerName yoursite.com

        ServerAlias *.yoursite.com

        DocumentRoot /var/www/yoursite.com

</VirtualHost>

Note that /var/www/yoursite.com is actually the name of a folder, i.e. “yoursite.com” there is a name of a folder. You don’t have to put the .com, but I like to in order to be very consistent.

Now in that folder put a file similar to that index.php file made in the previous Setup tutorial. Now go to www.yoursite.com or yoursite.com and you should see the same result, i.e. the information about your server. If you do, you’re money and good to go.

If you haven’t setup your domain on Godaddy to point to your server, do so now. I won’t go into deep detail about it because you can google something like “godaddy dns tutorial” to figure it out. But basically, you’re going to navigate to My Domains, and then to the yoursite.com domain, and then to “Manage DNS Settings” and then enter the IP address of your server near the top of the page, and save the settings. I won’t go into much about the technical terminology about how you’re essentially making your “A record” (i.e. a DNS record) point out your ip address. Just make it happen. It’s no big deal.

You may need to restart your server, so at the command line type:

# /etc/init.d/apache2 restart

It also may take some time for Godaddy to successfully point your domain at your server, but I’ve found it almost always to be instantaneous.

SETUP 3 - INSTALLING Yii & YOUR APPLICATION

This tutorial is all about getting Yii to work on your server. We’re going to optimize your server to best perform for Yii, install the Yii Framework library code, and generate the beginning of your application so it’s connected to all the framework code.

First run the following commands to install a tool called “APC” which is a caching application that makes PHP execute faster:

# pecl install apc

Now add the following lines at the bottom of this file /etc/php5/apache2/php.ini :

[apc]

extension=apc.so

apc.enabled=1

apc.shm_size=512M

Then restart Apache with the /etc/init.d/apache2 restart command

Also, in this file /etc/php5/apache2/php.ini  you were just in, you might as well change your time zone to UTC now so you’re running a common & consistent time zone for all the developers that may be working on your app. Google “UTC” if you’re not sure what that’s about. Search that file for “date.timezone” and change that line to:

date.timezone = UTC

Also, lower your error reporting in that file by ammending the following line to look like this (obviously search for the  “error_reporting” directive similar to how was done above):

error_reporting = E_ALL & ~E_DEPRECATED & ~E_NOTICE

Next, for the URL rewriting rules generated by your upcoming Yii application to work, execute the following command:

# a2enmod rewrite

That’s a simple command that installed a “module” to your Apache web server application. This application is called “Mod Rewrite” and it’s basically the most common Apache module. What it does is allow you to do things like hide file names such as “index.php” from your URLs, and generally aid in beautifying your URLs. Yii has a bunch of tools to automatically beautify your URLs, but it needs mod rewrite installed to do so. Specifically, yii will generate a file called .htaccess in your root application directory that will have these rules. It may be a hidden file, so you will have to unhide it to read its contents if you would like. Check that file out after you install Yii and your base application code in the following steps.

Now navigate to your /var folder and execute the following command

# cd /var

# svn co http://yii.googlecode.com/svn/trunk yii

That will install Yii here: /var/yii . That’s just the place I like to put it on all my servers so that I always know where it is. Remember this is the FaceySpacey formula. We do things in a consistent way so we know what to expect from server to server.


Also note that we can run the “svn” command because we installed the “subversion” application in first Setup tutorial. Subversion is another version control system. It’s one of the most popular ones, and it just so happens that Yii uses it. We don’t recommend it for development, but you need it to install yii like we just did. The benefit of using SVN to install yii is that you can run the following command to update your framework any time it’s improved:

# cd /var/yii

# svn update

In that command you navigate to your Yii code repository, and update its code.

Now, it’s time to generate the beginnings of your application. The idea is that Yii provides a command you can execute from the command line that will generate the folder structure for your application and connect it to the framework code. Execute the following from the command line:

# /var/yii/framework/yiic webapp /var/www/yoursite.com

To learn more about what’s generated, go here: http://www.yiiframework.com/doc/guide/1.1/en/quickstart.first-app

But generally, here’s the folder structure that will be generated:

testdrive/
  index.php                 Web application entry script file
  index-test.php            entry script file for the functional tests
  assets/                   containing published resource files
  css/                      containing CSS files
  images/                   containing image files
  themes/                   containing application themes
  protected/                containing protected application files
     yiic                   yiic command line script for Unix/Linux
     yiic.bat               yiic command line script for Windows
     yiic.php               yiic command line PHP script
     commands/              containing customized 'yiic' commands
        shell/              containing customized 'yiic shell' commands
     components/            containing reusable user components
        Controller.php      the base class for all controller classes
        UserIdentity.php    the 'UserIdentity' class used for authentication
     config/                containing configuration files
        console.php         the console application configuration
        main.php            the Web application configuration
        test.php            the configuration for the functional tests
     controllers/           containing controller class files
        SiteController.php  the default controller class
     data/                  containing the sample database
        schema.mysql.sql    the DB schema for the sample MySQL database
        schema.sqlite.sql   the DB schema for the sample SQLite database
        testdrive.db        the sample SQLite database file
     extensions/            containing third-party extensions
     messages/              containing translated messages
     models/                containing model class files
        LoginForm.php       the form model for 'login' action
        ContactForm.php     the form model for 'contact' action
     runtime/               containing temporarily generated files
     tests/                 containing test scripts
     views/                 containing controller view and layout files
        layouts/            containing layout view files
           main.php         the base layout shared by all pages
           column1.php      the layout for pages using a single column
           column2.php      the layout for pages using two columns
        site/               containing view files for the 'site' controller
           pages/           containing "static" pages
              about.php     the view for the "about" page
           contact.php      the view for 'contact' action
           error.php        the view for 'error' action (displaying external errors)
           index.php        the view for 'index' action
           login.php        the view for 'login' action

You should now be able to visit yoursite.com and see the basic Yii web app  that was generated. That is, if you previously connected your domain to your server, and accordingly the path to /var/www/yoursite.com.

The next thing to do is to follow the instructions on the above link to the Yii site. I won’t re-write it all, but I’ll give you the high level explanation you need to get the picture so you know what you’re looking at as you dive into the deeper details and specifics there. Basically, that tutorial will describe how to connect your new application to your MySQL server and database (which you previously installed). Then it will describe how to run a web interface bundled with Yii that will automatically generate base code based on the tables in your database. Right now would be the time in the development process to build all the tables your database needs. As you’ll read in the product and speccing tutorials, it’s very important to prepare as many of your tables as you can ahead of time. If you’ve specced well, you should be able to know exactly what tables you’ll need to accomplish the product goals.

I’d like to point out how configuration works. In Yii, and many software applications, you have a central and single “configuration file” where you can configure the specifics of your application, i.e. database connection details. What this does is make it so you don’t have crucial specifics strewn throughout your codebase that are impossible to find at a later point in time. This way at any point in time you know just to go check your configuration file and make adjustments there, rather than spend hours hunting down hidden “switches.”

Another thing to note is specifically what the yii code generation tools--called “Gii”--are doing. Specifically they build the base code you need in your Models, Controllers and Views. The most important thing here is that it shows new Yii developers how to build applications. It serves as a great starting point. Eventually you may end up not using the code generation tools, but nevertheless in the beginning, it will point you in the right direction. Make sure to examine all the files generated and what’s in them. Check your Models, Controllers and Views folders. They will all be in /var/www/yoursite.com/protected/ .

DEVELOPMENT TOOLS 1 - VERSION CONTROL (Mercurial)

So if you’ve read the Setup tutorials, you’ve heard me mention “version control.” Version control has typically been called a “time machine” to look at your code. What that means is you can look at your code at any moment time as it has been developed. You can do things like revert back in time to what your code looked like at a previous point in time, i.e. “roll back” your code to how it was last week. Or, just look at what your code was a while ago before you altered it. It serves the purpose of giving you confidence to do things like delete and replace old code with new and better solutions. So in the case that the new code isn’t quite right, you can go back and look at how it was before. It also greatly aids multi-developer teams. It allows each developer to work with an unchanging set of code. So that means if another developer changes something, it won’t break your code. However, there will be a time when you have to merge your code with the code of other developers. What this does is define a clear cycle of coding without worrying about changes, and then merging with everyone else. When you merge, your version control system will try to do it automatically, but if there are conflicts it will compare your code with the code of other developers and allow you to make edits so that you don’t break each other’s code. That’s the idea.

The most popular version control systems these days are SVN, Git and Mercurial. We, at FaceySpacey, use Mercurial. SVN is a little older. Git and Mercurial are very comparable. They allow for what’s called “distributed version control.” I won’t go into what that means too much right now, but I will say that Git has been compared to the MacGyver of version control and Mercurial to the James Bond of version control. What that means is Git has more features (and therefore more to learn and figure out), whereas Mercurial has less features but is easier to get up and running with. The features it does have are very precise and solve what it is you will actually need most of the time really well. The reason we use Mercurial is because it integrates nicely with our bugtracker, Fogbugz. Fogbugz’s makers, Fogcreek, has a complementary product called “Kiln” which works in conjunction with Fogbugz. Basically it allows you to associate committed code to fixed bugs and completed tasks/features within Fogbugz.

So here’s how we use Mercurial.

1) Signup for Kiln here:

http://www.fogcreek.com/kiln/

They have a free startup version for 2 developers. Once you create your account, you’ll be directed to create your first repository. Create it. Some directions will be provided about how to “push” your code to this storage space on Kiln’s servers for your code.

2) Those directions will look like the following basically. At the command line navigate to your code and execute the following commands:

# cd /var/www/yoursite.com/

# hg init

# hg add

# hg commit

# hg push https://yoursite.kilnhg.com/repo/project-name/Group/repo-name

That will take the code on your server (or your local host if that’s where your’re working) and send the code to your storage space (i.e. respository) on Kiln’s servers. In essence, Kiln will keep a back up of all your code--and of course with all the “time machine” magic previously talked about. In other words, it will store snapshots of your code at all points in time--well, specifically, after all commits. A commit is made every time you type “hg commit” at the command line while within your application directory. If you type “hg commit -m ‘some notes’” you can leave some notes about the recent changes you made, and then you can easily see what code is being commited within the Kiln web interface.

The next thing to note is that in the file, /var/www/yoursite.com/.hg/hgrc, you can permanently enter your Kiln login credentials so that with every commit and push to the Kiln server you don’t have to enter the login credentials again:

[paths]

default = https://yoursite.kilnhg.com/repo/project-name/Group/repo-name

[auth]

kiln.prefix=https://yoursite.kilnhg.com/repo/project-name/Group/repo-name

kiln.username=your-kiln@email-address.com

kiln.password=yourpassword

[ui]

username= your-kiln@email-address.com

password=yourpassword

The /.hg folder fyi may be hidden, so make sure to unhide your hidden files while in your root application directory to see it.

The last thing to do is to navigate to another hidden file /var/www/yoursite.com/.hgignore and add the following lines (create this file if it does not exist already):

syntax: glob

runtime/**

assets/**

Those lines will make it so you don’t commit code that is unique to each computer that has the code on it. You may end up having an /uploads folder in your root application directory. If my app has functionality for users to do things like upload photos, i’ll make it so those large images are also not committed and pushed. Photos are big files and will make it so your commits/pushes take a long time, and won’t be needed on the computers/servers of other developers since they’ll have their own.

So that’s basically it. One of the biggest benefits of doing this is you don’t need to worry about losing all your code if your server goes down. All you’re going to have to remember really after it’s installed is to type “hg commit -m ‘some message’” after you write new code, and “hg push” to push it to the central repository. And then “hg pull” and “hg update” which you run to pull in code commits other developers pushed to the main Kiln repository. You’ll also at times have to type “hg merge” but the beauty of mercurial is that when you run any one of these commands, if there is a problem, mercurial will let you know at the command line and suggest other commands such as the “hg merge” one that you should execute.

Let me summarize the common flow:

PUSHING YOUR NEW CODE OUT:

# hg commit

# hg push

PULLING OTHER DEVELOPERS’ CODE IN:

# hg pull

# hg merge

# hg update

That’s basically all you need to get productive quickly. When you get serious about using Mercurial, read the following longer tutorial by the Joel Spolsky, the creator of Fogbugz and Kiln (as well as Stackoverflow). He’s a prolific software developer that got his reputation from his work at Microsoft, specifically on the Excel project. Joel Spolsky’s the man. Research/google him.

http://hginit.com/

DEVELOPMENT TOOLS 2 - IDEs (Netbeans)

When learning about coding and how to code, one of your initial questions will be simply: “Where do I do my coding?” The reality is you can do it in a basic text editor like Notepad on windows, or Gedit on Linux, etc. However, there are many applications, IDEs (Interactive Development Environments), that provide a bunch of extra functionality to make coding easier. Here’s a list of basically all the PHP IDEs:

http://en.wikipedia.org/wiki/Comparison_of_integrated_development_environments#PHP

Our recommendation is Netbeans. Why? Well it’s the one I’ve found to be most popular among Yii developers, plus I’ve tried them all and compared all their features blow for blow, and I found it to be the beast. It has built-in Mercurial support, support for debugging with Xdebug (which we’ll cover in another tutorial, great code completion support, refactoring tools and more.

You can download it here: http://netbeans.org/ . Well, here’s the download page (download the PHP version obviously):

http://netbeans.org/downloads/index.html

Netbeans is open source. It has many plugins to augment its functionality, and its well-maintained with constant improvements.

This is going to be a short tutorial, and it’s more of a recommendation. But I will share the main things to expect from Netbeans (and most IDEs):

1) Code Completion - what this will do is display menus as you type code to help you complete your code, i.e. offering hints of what you might type next. When coding, it’s not about remembering every function or method, etc, that you may type. It’s about generally knowing what you’re doing. With the internet at your fingertips, it’s all about looking up a solution you know exists (perhaps by reading these tutorials) or even a solution you previously used to remind yourself. Similarly with code completion, you’re given the names of possible solutions based on what you’re typing. The solutions will generally come from the Yii framework powering your application (or your own code). The idea is that the IDE is knowledgeable about all the methods, properties, etc that lie deep within the Yii library code. So you don’t have to worry about remembering it all.

2) Code Hiding - you can expand/collapse blocks of code that you’re not currently working with to make it easier to focus on what you are working with.

3) Code Navigation - Netbeans provides lists of all the methods and properties in your current PHP class, so you can navigate around the code by browsing a simple list of the main (hopefully informationally named) methods/properties/etc.

4) Refactoring - you can do things like change the name of a method everywhere it is used in your code by changing its name in one place. And more. The general idea behind refactoring is that you often come up with more concise ways to code solutions after you’ve already developed a partial solution. Netbeans makes it easy to globally make a change across all your code.

5) Debugging - Debuggin is the process of executing your code in your web browser while your IDE “steps” through the code. That means you can visit your website, and then watch basically an arrow point to each part of the code as it’s executed. What happens is your browser hangs on a white screen, while you watch the sequence of your code execute step by step. This is required tool for all FaceySpacey developers. It allows you to pinpoint where the problem is, rather than see an error page in the browser and wonder where the problem is. I won’t go to deep into debugging right now, but just imagine yourself being able to execute a script, and watch what values are being dealt with in just one block of code in perhaps many blocks of code in the execution without having to worry about those other blocks.

6) Formatting - this is perhaps the most basic feature of any IDE, but a very important one. Netbeans will automatically space and tab words apart from each other in a consistent fashion so your code always is structured similarly and is therefore easier to read.

7) File Browing - Netbeans makes it very easy to navigate your tree of files in your application, and add new files, etc.

Netbeans offers a lot more features, but that should give you an idea of what its purpose is. Get it immediately, and don’t look back.

DEVELOPMENT TOOLS 3 - Project Management Software (Fogbugz)

There are many project management tools to choose from. They’re often called simply “bugtrackers.” Here’s a Wikipedia comparison list of all the tools too choose from:

http://en.wikipedia.org/wiki/Comparison_of_project_management_software

37signals’ Basecamp has become the poster child of such software. It’s too basic of a tool for real software development in our opinion. Our pick here is Fogcreek’s Fogbugz. Here are the main reasons:

1) Custom Task/Bug Organization - Fogbugz allows you to create lists of tasks/bugs and group them in an almost infinite number of ways, i.e. by area, priority, tags, milestone, assignee, and many other criteria. However, that’s not the magic. The magic is you can have multiple “views” into your tasks accordion to different criteria. Fogbugz calls these “Filters.” In essence, the tasks exist in the system and are tagged with various criteria. Then you can build Filters that sort, group and filter the tasks shown according to a configuration of all that criteria. And then you can build as many of these filters as you want. For example, you can see just all tasks for Project ABC with priority 5+ in the current milestone that are past due. You can then share these filters you create with other developers so you know you’re all looking at the same system.

2) Plugins - Fogbugz has a great plugin system where 3rd party developers can enhance it. One popular once is Kanban. Search in google images “Kanban chart”: http://www.google.com/search?q=kanban+chart&hl=en&prmd=ivns&tbm=isch&tbo=u&source=univ&sa=X&ei=9VwlTsL0DIPW0QHsr6TrCg&ved=0CBgQsAQ&biw=1440&bih=790 to see what it is. It’s basically a chart with several vertical columns, and then you move post-it notes that correspond to tasks across these columns from left to right as they get closer to true completion. So the Kanban plugin helps display your fogbugz tasks in a similar visual.

3) Integration with Mercurial - Fogbugz’s sister product (as mentioned in the Version Control tutorial) Kiln is deeply with Fogbugz. It allows you to associate actual committed code with completed (or near-completed) tasks. It also allows you to do code reviews. It’s pretty sick.

4) Evidence-based Scheduling - Fogbugz can produce pretty graphs that estimate when projects/tasks/milestones will be completed based on the measured efficiency of your developers and what tasks they’ve already completed. It takes a lot of discipline to use this properly, as you need to do things like estimate how long tasks will take and mark how long they ultimately take you, but if you can get your developers into a groove using this, you can get great estimates of when your milestones will be reached.

5) Wikis - Fogbugz has wikis that can be two-way linked between tasks. So you can produce documentation for your code or product and closely correlate it to your task.

6) Email Support System - It comes with an email support system that turns any emails into tasks in your system automatically, and your developers can do things like respond to bugs inside of fogbugz just like they would any other task, and the person that reported the bug (or complain) will get an email. And of course that thread can continue accordingly.

7) Forum System - It has a forum system that also interlinks with the bugtracker similar to the wiki system.

8) Snapshop plugins - There are some great plugins that allow testers to take screenshots of issues your app is having and automatically send the screenshot (with some notes and other tagged criteria) to the bugtracker at the core of Fogbugz.

9) Nested Tasks - Tasks can have sub-tasks for basically an infinite # of tiers (well, i think it’s 8 tiers). A lot of bug trackers only have 2 tiers of tasks, i.e. a group and a list of tasks in it. Fogbugz allows you to easily have child and parent tasks, and move tasks around between different parents.

10) Quick Notation - Fogbugz has a quick way to enter tasks one after another in a quick to do list. This is very powerful for just banging out your task list quickly.

The list goes on. We highly recommend it. Check out all the features here:

http://www.fogcreek.com/fogbugz

Now I’m going to end this article explaining the importance of bug-tracking and project management software in general. The importance is simple: one of the key skills required of a great developer is storing many to-dos in their head at a time. But the reality is it’s impossible to store them all. Project management software allows developers to focus on doing the actual work. They’ll inevitably always find sub-tasks they must remember. So help them make it so those tasks they have to remember are very few and at a very granular level for a clear single task. For product owners (i.e. the non-technical participants in the project), it will give you insight into the progress of your developers. It’s pretty self-explanatory. The biggest takeaway is just get Fogbugz and don’t spend 2 weeks researching all the bugtrackers like I and many startup guys have done. It is sort of a right of passage to study them all for any Web 2.0 guru, but really, just get to coding your app and take my word for it: Fogbugz is the shit!

DEVELOPMENT TOOLS 4 - Debugging (Xdebug)

Debugging is perhaps the most important part of software development. If you’re not a coder yet, and you manage some coders, you may be inclined to measure their productivity by how many lines of code they’ve coded, but the reality is most of their time is spent hunting down bugs and often changing one line of code. So therefore tools to track down those bugs are very important.

Debugging tools allows you to isolate the problem area and “step” through its lines of code to see quickly find the precise problem. You can do things like see the values of each variable at each line of code until you see where the value is not what it should be.

The best and most popular tool for PHP debugging is called XDebug. You can check it out here: http://xdebug.org/ .

Installing Xdebug can be quite problematic. Here’s the best tutorial I’ve found, and exactly what I used to install it: http://devzone.zend.com/article/2803

The basic idea is you install the Xdebug application on your server, and then tell PHP it can use it by configuring you php.ini file you’ve seen edited in the Setup tutorials.

The next thing you need to do is configure Netbeans to make use of it. Here are the tutorials to do so:

http://wiki.netbeans.org/HowToConfigureXDebug

http://netbeans.org/kb/docs/php/debugging.html

When completely installed, which again is the hardest part, you finally get to learn the joys of debugging. The main idea is you can watch your script execute while the browser hangs and basically press pause/play buttons to step through your code line by line, while viewing in a window the values of all the variables in the current scope.

You can do things like dive deeper into called functions or skip over them and just step through the current top level client code. You can go as many layers deep as you want and back out as many layers back as you want. So that means if a function or method is called, you can choose to step through all the lines within it, or just treat it as one line that you skip over and move to the next, i.e. if you deem it not to be problematic. But if you determine that a specific method call is where the problem is coming from, you can dive into it and go line by line through its code while watching the values of variables used within it.

Other things you can do are create “breakpoints” which are points in the code sequence the debugger should stop at while it’s playing through your code. Think of the debugger like a music track. You can basically say at 1 minute 33 seconds pause, or rather at line 77 pause. And then take a quick peak at what’s going on. You can set several break points, and just pause/play until you reach them, without having to waste your time stepping through other lines you’re pretty sure are kosher.

You can also specify “watches,” which are basically variables and properties, whose values you’d like to watch more closely. Xdebug within Netbeans unfortunately is a little buggy, or rather, is just not capable of tracking all variables. I think it’s because it just takes too much computing power. That’s why it allows you to specify “watches” that will contain the values of variables/properties you’re really interested in.

The last really important thing it does is maintain a “call stack” for you. A call stack is treed outline of all the methods called and the methods they call and so on. The Yii framework will produce similar call stacks when your pages produce errors. The idea is you can track the code execution path in terms of methods called. So one method usually will call several methods in it, and those methods will do the same and so on. And if there is a problem, you’ll be looking at the last method called before the error or exception occurred. When you’re there you can get a list of all the previous methods called to get to that point. This way you can go up and down the tree looking for other factors that might have caused the problem, without having to examine methods that aren’t part of the sequence.

Again, Debugging is very important. Without it, developers do this: they make their code echo the value of variables--often arrays--in their code that they think are causing the problem. When they do so, they stop the script from executing further. To do this they will enter something like var_dump($variableName); exit; in their code to make the  script echo out to the browser the value contained in $variableName on to a white screen, and stop all else. This is problematic because you then have to remove that code, or comment it out, and if you comment it out, you’re left with lots of extra code that won’t be used when the script is in production and used on a live site. Debugging adds a layer of extra tools to do all this for you without cluttering up your code. Master it asap. If you know Javascript, a good place to start is with the debugger built into the Firebug plugin for Firefox since it takes no installation, and as I said before Xdebug is hard to install.

DEVELOPMENT TOOLS 5 - Unit Testing (Using Yii Tools)

Unit testing is the testing the of individual code blocks at a granular level. Therefore tools to aid this process make it very easy to isolate these blocks of interested and make sure they’re kosher. “Test Driver Development” is a methadology where you code tests before you even write code. For new developers--that these tutorials are written for--it’s really hard to get why it’s so important since you usually want to get to coding your features immediately. That’s why I won’t go too deep into it yet, but I will say that for large teams and apps already in production iterating into post-launch phases it’s very important. The reason is because you can run tests that will verify past code you’ve written still works. As you improve upon your app and add new features, it’s inevitable that you will break old code. With a proper suite of tests for your most important features, you can quickly generate a report that lets you know if anything broke.

The way unit testing works is generally that you define sets of input, then the test passes the input to a block of code, waits for the output, and then tests that the output equals what you want it to equal. You have to write code to setup what the input is, and you have to write code to test the values of the output and if they match your expectations.

Yii offers built-in testing tools (based on PHPUnit). To install them and learn how to use them, read these tutorials on the Yii site:

http://www.yiiframework.com/doc/guide/1.1/en/test.overview

http://www.yiiframework.com/doc/guide/1.1/en/test.unit

With this birds-eye-view overview you should know when this will become important. To me, the biggest thing is the mindset that unit testing cultivates. It helps you imagine your code in parts, rather than features. It lets you visualize the motor, the steering wheel, etc, if we were to use a car metaphor. It helps you pin-point how each part should interface with other parts so that you can get a rock solid interface between sets of code so that less breakdowns happen. It helps you know where the problematic parts will be, i.e. what points of interface may be weak or strong.

In another article I’ll cover Functional Testing, but not in this series. However, I’d like to point out the difference: Unit Testing is all about automating the testing of blocks of code, methods basically, while Functional Testing is all about automatically simulating a user on your site and catching any issues at the graphical user interface level. In my experience, doing Functional Testing is a lot more difficult to pull of and without the gains of Unit Testing. Functional testing is very appealing to non-technical product guys that don’t trust their developers--at least the overall concept is. Functional testing is great when your app is truly done, and you want to keep it that way as you add new features. It’s not as useful in the development stage and just getting to your initial launch, for which these tutorials are mainly written. It’s hard to prepare useful functional tests when your app barely works. Whereas unit testing--or especially test driven development where you write the tests first--is key to giving developers a mindset where they visualize their code in chunks. Overall, unit testing allows developers to really focus on their tasks and guarantee that what they’ve been assigned to do is as closed to perfect as possible. It requires great product specs, as do most aspects of software development for GUI heavy apps, so that you can also create great tech specs where you pin-point precise pockets of code to write. When a project can be broken down that granularly, unit testing does wonders by helping developers focus on and insure their assignments will interface with the assignments of other developers perfectly, or at least in the way the other developers expected.

KEY TECH CONCEPTS 1 - CRON JOBS

Cron jobs--or more accurately “Crontab”--is a common Linux application you’ll hear about early on in your ventures into web development. Many crumby hosting providers provide a way to trigger “cron jobs” in entered intervals. If you’re running your own server, you’ll type a command such as:

# crontab -e

and see a simple text file that line by line lists scripts to trigger in given intervals. For example, one might like this:

1 11 * * * commandname >> /var/log/log-name.log

That one for example will trigger the command, “commandname” every day at 11am and record any output produced by that command into the file log-name.log.

The idea behind cron is simply that you can trigger routine tasks in recurring intervals. Other examples of such intervals are every minute, every 30 minutes, once a week, once a month, etc.

You can even trigger PHP scripts. Yii has tools to create “console applications,” i.e. applications/commands you can trigger from the command line of your server. To learn more about them, check out the tutorial on the Yii site:

http://www.yiiframework.com/doc/guide/1.1/en/topics.console

To learn about using cron in Ubuntu, here’s the official Ubuntu tutorial:

https://help.ubuntu.com/community/CronHowto

Overall, the thing to note is that cron is extremely easy to use. It’s not anything crazy. Write a PHP script using the Yii console application tools, and trigger it with a simple line in the crontab file. That’s it. The next thing to note is that cron isn’t the solution for everything. Often Daemons may be the real answer, and we’ll cover that in the next article. The general idea is that cron scripts can often overlap and get clogged, whereas daemons are constantly running in realtime and you can write logic that solves how to deal with these jams.

I’ll end this tutorial with an example of what cronjobs are good for so you know what challenges to look out for that are nicely served with an entry in your crontab file as a solution. Imagine you want to generate a report each day, maybe with the # of new user signups and other such data. Well, cron is perfect. Trigger your PHP script that will check the database for the # of new users since the same time the day before and email the result to yourself. Or perhaps, you are seeding your site with content from RSS feeds. You can write a PHP script to check these RSS feeds daily (or hourly or whatever) daily and insert the new articles in your own database of articles.

KEY TECH CONCEPTS 2 - DAEMONS

A Daemon is a Linux program that is constantly running in the background. In fact, Apache and MySQL are both Daemons. They sit around waiting for connections, i.e. Apache waits for remote web request connections to your sites and MySQL waits for connections from your PHP code trying to select and insert stuff into your database. One cool thing to note is that most the Daemons on your Ubuntu Linux server store logs of what they’re doing in sub-folders and files within /var/log .

Most Daemons are written in C. However there are tools to make it very easy to create powerful Daemons in PHP.

I won’t go into the technical details of writing them because the following tutorial is fantastic:

http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/

Basically that tutorial describes tools the author made to create daemons, how to install the tool, and how to put it to use. Installing the tool is very easy. Just enter the following command at your command line:

# pear install -f System_Daemon

That requires the pear application to run, but fortunately you already installed that if you followed our Setup tutorials.

System_Daemon is a “pear package.” Pear packages are bundles of additional code you can attach to your PHP application that gives you additional functions/classes/methods to use. Pear itself is basically a tool designed for nothing bug augmenting the tools available to your PHP installation. You will use it often to install 3rd party PHP tools.

In this case after you’ve installed System_Daemon, you have access to a few a methods of the System_Daemon class that do all the real work of the Daemon, and the result is you can basically think and code in PHP terms you’re used to.

If you read that tutorial, you’ll see that the main function it offers is to loop through a task in an interval you set, i.e. it will attempt to perform the same task over and over again. You can then write code to do nothing if your code determines there is nothing to do. For example, if you want to check every moment for new users in your system and email them every time one is found, you can do so, and decide to do nothing if none are found. You can also safely break the system down if some error occurs.

You can also make it so your daemon script runs automatically every time you boot up your server. That way you don’t have to remember to turn it on and off again.

Another cool thing you can do is you can monitor the log file it’s writing too in realtime via the following command:

# tail /var/log/your-log-file-name.log

In the php code you write you specify the log file to write to in a simple configuration array and the daemon will write to it as it loops through the task its assigned. It will record each loop it makes, any errors, etc. So therefore you can monitor that file with the “tail” command and see what the daemon is doing in realtime. At FaceySpacey we really love the tail command. It puts what’s going on in your server at your fingertips. Often many things are going on in your server, and you’re not sure if it’s working or not, and you want to know immediately, possibly while you’re doing something to trigger breaking it. So for cron-triggered scripts and daemons this is very important since you’re not sitting there watching the results output to your screen. It’s all happening in the background. So “tail” is your window into what it’s doing.

Setting these Daemon tools with Yii can be a little problematic. I’ll cover it in detail outside of these begginer set of tutorials, but the basic idea is that you put all the code you see in the Daemon tutorial (linked to above) into a Yii console application script. You can then trigger your console application script like you would normally from the command line, but then a Daemon is triggered and set into motion in the background. It’s really quite a powerful combination since you get access to all the Yii ActiveRecord tools to work with your database and models.

KEY TECH CONCEPTS 3 - DOCUMENTATION (Doxygen)

Documentation is a required component for any long-term software application that has developers coming and going, or generally an expanding team. You won’t just have to explain code to new developers, but also to yourself and your current developers when they look back at what they did even just a month ago.

The hardest part is maintaining documentation as your code changes. Often documentation can become outdated, yet it will still be there and you’ll be looking at it as if it explains the current code, i.e. the code has changed but the documentation has not kept up.

The way to solve this problem is to automate documentation generation based on code comments (i.e. generate documentation from code comments), and to follow standard documentation practices, i.e. “PHPDoc.” PHPDoc is the formal standard for commenting PHP code. It’s a simple syntax to comment classes and their methods. So if you keep your comments up to date for just your classes and methods, you’ll be good to go because of the following tool I’m about to describe that will automatically generate a mini-site of documentation based on those comments.

Doxygen is the tool we recommend to generate that mini-site. Here’s it’s site: http://www.stack.nl/~dimitri/doxygen/ .

To use it enter the following commands from your Ubuntu command line:

# apt-get install doxygen

# apt-get  install graphviz

# apt-get install mscgen  

# doxygen -g

When you type doxygen -g it will generate a file in the current directory called “Doxyfile.” That file is a very large configuration file. You need to edit this file. Here you enter all sorts of options, but most importantly the directory where your code is. You do so by specifying a simple “input” directive, as explained here:

http://www.stack.nl/~dimitri/doxygen/config.html#cfg_input

To see all configuration options go here:

http://www.stack.nl/~dimitri/doxygen/config.html

After you’ve set all your options, simply run the following command (where “Doxyfile” is the name of the config file):

# doxygen Doxyfile

The doxygen program will then generate a mini site in the location you specify with the “HTML_OUTPUT” directive: http://www.stack.nl/~dimitri/doxygen/config.html#cfg_html_output .

Then obviously you setup Apache to display this site on the internet, and boom you have a mini-site with all your documentation. Just re-run this command any time you want to update it, and it will update it. This site will list all your classes, methods, and interlink pages together nicely, even generate all sorts of UML diagrams. UML diagrams are diagrams explaining code. Learn about it: http://en.wikipedia.org/wiki/Unified_Modeling_Language . Otherwise, all your code comments will be in there as well associated with their corresponding method or class. You of course get several ways to browse your documentation pages: by class name, method name, searching, etc.

That all said, the Yii Framework itself has awesome documentation in its “class reference” on its site. It’s obviously automated as well, and they very possibly use Doxygen themselves, plus a few custom enhancements to the generate mini-site. I would love it if the contributors to the framework would share their code documentation tools as a feature of the framework itself so you could easily generate documentation of your Yii apps. I’ve been meaning to bring it up in their forum and probably will some time soon. If that ever comes out, forget Doxygen. Until then, Doxygen is our pick at FaceySpacey--and yes over PHP Documentor: http://www.phpdoc.org/ . We’ve used both extensively and Doxygen is a lot better. Doxygen also happens to support many languages besides PHP. You’d expect the one just for PHP to be better, but it isn’t.

KEY TECH CONCEPTS 4 - APIs

An understanding of APIs is key to modern web development. Prolific East Coast investor (from Union Square Ventures), Fred Wilson, I remember once mentioned in a video that he forecasts the future of the web being all about mashups of APIs. What that basically means it that apps will be getting data from tons of places (currently Facebook, Twitter, etc) and sending data back. These days you can build tools using other tools that are mashups. For example Twitter Feed helps you post to Facebook and Twitter from your RSS feeds. So basically you’re going indirectly through another mashup to accomplish your automated posting to the said social networks. That’s a basic example, but the basic idea is still the same: everyone’s building stuff on top of other applications, and people are building on top of that and so on.

So what is an API? An API is a programmatic way to send input to another web application and get output back over the internet. So rather than visiting a web page in a URL, your application can visit special URLs that return data in consistent formats that your app can then interpret and use to go about its business. It’s a way for one app to communicate to another. This is so powerful that large soon to be public companies like Zynga have made billion dollar businesses using APIs of other companies, i.e. specifically Facebook. Zynga’s going to go public before Facebook! Isn’t that crazy.

Back to what Fred Wilson was saying. He’s basically saying that an internet behind the scenes is emerging. It still uses the HTTP protocol like your web browser does, but its your app code that’s doing the communication to accomplish its own unique goals. As a result we have entire companies, like the new Ness (http://www.likeness.com), which do nothing but mine data from other sites and build an intelligence based on that information. Ness, for example, plans to harvest data from tons of places to build a minor form of artificial intelligence that will help you search and get results based on your tastes. A lot of guys have tried to do this to a degree, but it’s about time for this to get really real--because of the shear amount of data you’re putting out on Twitter, Facebook, iTunes, etc, about what you like.

So how does this actually work in an actual application? Basically you write code to ping a URL, and in the URL you specify for example a user ID of a Facebook user, and you can get their information in a consistent structured format that your code can then parse. For example here is the basic information about one of the most famous Facebook engineers, Bret Taylor:

{
  "id": "220439",
  "name": "Bret Taylor",
  "first_name": "Bret",
  "last_name": "Taylor",
  "link": "http://www.facebook.com/btaylor",
  "username": "btaylor",
  "gender": "male",
  "locale": "en_US"
}

You can ping the Facebook API at the following endpoint URL to get that data about him:

https://graph.facebook.com/btaylor

That data happens to be public. For private data you would specify basically a password in the URL (that you usually have stored in your database) to get access to that facebook info. We’ll cover in another article Facebook authentication, but basically Facebook, Twitter, etc, all provide ways for end users in their browser to pass you a special password (“access tokens”) to gain access to their data and post updates/tweets on their behalf.

Back to the structured data above. As you can see the data is presented in a consistent format. All users will have a gender, first_name, etc. It will all be presented in a similar format. Therefore you can write code to iterate over that list of data and grab each value by its key, i.e. you can expect to get all first names by the key, “first_name” and so on. That’s the idea.

When you submit data, you also get a response, e.g. that what you posted was successful. For example, if you’re using the Twilio API to send SMS text messages you will get a response like this:

<TwilioResponse>

    <SMSMessage>

        <Sid>SM90c6fc909d8504d45ecdb3a3d5b3556e</Sid>

        <DateCreated>Wed, 18 Aug 2010 20:01:40 +0000</DateCreated>

        <DateUpdated>Wed, 18 Aug 2010 20:01:40 +0000</DateUpdated>

        <DateSent/>

        <AccountSid>AC5ef872f6da5a21de157d80997a64bd33</AccountSid>

        <To>+14159352345</To>

        <From>+14158141829</From>

        <Body>Jenny please?! I love you &lt;3</Body>

        <Status>success</Status>

        <Direction>outbound-api</Direction>

        <ApiVersion>2010-04-01</ApiVersion>

        <Price/>

        <Uri>/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/SMS/Messages/SM90c6fc909d8504d45ecdb3a3d5b3556e</Uri>

    </SMSMessage>

</TwilioResponse>

And as you can see the <status> node says it was successful, and your code can now continue as normal because it knows it executed its job of sending an SMS text message successfully. in the <Uri> node you receive an ID # for that SMS text message so you can refer to it later. You could store that in your database and request another API endpoint url and get back the contents of this text message, i.e. similar information to what you see above. Maybe you want to produce a history of all text messages sent through your app--so that’s why you would do that.

That’s a quick runthrough of what APIs are about. If you plan to post tweets to twitter and updates to Facebook with your App, you’re going to want to understand how APIs work even if you’re not going to be a coder. More specifically, you need to be able to read API documentation, e.g. like the one Facebook provides for their “graph API”:

http://developers.facebook.com/docs/reference/api/

If you can read the documentation you will know specifically what you can’t and can do, and can therefore better instruct your developers of what to develop. You’ll avoid sending them on a wild goose chase to code something Facebook won’t even allow you to do. I’ve seen so many failed companies spend ages thinking they can do something they can’t, and waste money forcing developers to figure it out on your dime.

To read API documentation you need to understand 3 things:

1) PARAMETERS - the data you provide to the URL endpoints, and what parameters are available and what types of values are accepted. These parameters basically configure what sort of output you should expect. They are the input, just like parameters to functions in PHP.

2) RESPONSE FORMATS - above you saw 2 types of response formats: JSON and XML. That’s basically all you’ll need to know. It’s how the response is formatted. If you can examine these tree structures, you can see what sort of data you can get out of the APIs you’re using.

3) POST vs GET - i’ve been referring to these URL endpoints as the only way to supply input parameters, but the reality is you can pass more parameters outside of the URL via “POST fields.” I won’t go into it at a deep level here, but I’ll give you the gotcha you need to know: basically you can attach more values and send them along with the URL you request. That’s it. So instead of having parameters at the end of the URL like this ?key=value&key2=value, you’ll send them in similar pairs but as POST fields. In PHP you’ll use a tool called cUrl to aid you in attaching these key/value pairs.

After you understand that, you’ll be able to read the documentation of very many APIs very quickly. They’re all quite similar. Study Facebook’s and Twitter’s until you get the hang of it.

LINUX COMMANDS  1 - Using the Linux Command Line

Basic knowledge of the Linux command line is key if you want to have any luck setting up a system to display your php code. Though on Windows and Mac (and Linux) you can install a desktop application that will basically do it all for you:

http://www.apachefriends.org/en/xampp.html

We don’t recommend it for pro development. XAMPP is cool if you’re learning PHP. Fine. But we’re assuming the readers of these tutorials are serious about getting their application production ready. So again, if you want to just get practicing PHP, XAMPP may be for you. Go install it. It’s really easy.

For everyone else, lets continue delving into the base requirements (i.e. most common commands) you need to know to run a professional Ubuntu setup (note: I actually started with XAMPP myself).

To navigate around directories use “cd” like this:

# cd /var/www

That will take you to the /var/www directories.

# cd ..

will take you one directory lower back to /var. And when in /var if you type

# cd www

that will take you back to /var/www. I.e. when you’re in a directory you can move to its sub-directories by simply typing its name after “www” rather than the complete path.

To edit files in a text editor, type:

# vim filename

To move files type:

# mv /var/www/file-name /var/file-name-moved

That will move the file name and change its name. To simply change the name of a file of your current working directory type:

# mv file-name new-file-name

To copy a file in a similar way type:

# cp /var/www/file-name /var/file-name-copied

To delete a file type:

# rm file-name

or if not in the current working directory:

# rm /var/www/file-name

To extract a gzipped archive (i.e. the most popular archive format on linux) type:

# tar -xzvf archivename.tgz -C result-folder-name

To compress a directory and all its sub-directories and files type:

# tar -czvf archivename.tgz input-folder-name

The extract and compress commands are so important because so often you’ll download compressed libraries of code you want to use, and of course you often want to back stuff up. It’s clearly the equivalent of unzipping and zipping up folders/files on your Mac/Windows desktop computer that you’ve been used to doing.

The next very important skill is being able to change permissions of your files and folders. For example, often you’ll want your files accessible by Apache, or more specifically the Apache user group, which is called “www-data”. And of course you’ll often want to protect files for security reasons. Here’s how you change the group that owns a directory and all its sub-directories and sub-files:

# chgrp -R www-data yourfolder

And to change the user do this:

#chown -R root yourfolder

The -R specifies to do it recursively, i.e. to get all the sub-folders and the sub-folders’ sub-folders and so on. Look up what “recursion” is some time: http://en.wikipedia.org/wiki/Recursion . It’s an extremely important programming concept.

Next, now that you have groups and users that own your files, you can adjust the permissions of these files like this:

# chmod -R 777 yourfolder

That will give all users, groups and the public read/write access to the file. To give just the user owner read/write access type:

# chmod -R 755 yourfolder

The first number corresponds to the permission of the owner, the second the group, and the 3rd the plug. 7 is the most loose permission and 5 is tighter. 6 is in between obviously. There is also an alternate sytax for creating such permissions. Google “Chmod tutorial” some time to learn more.

LINUX COMMANDS 2 - More Linux Commands

Let’s dive a little deeper into some more commands, building on what we just explored.

To list all users in the system open up the following file:

# vim /etc/passwd

If it’s not quite clear, the idea is Linux allows you to have multiple users. Remember in these tutorials we’ve been logging in as the “root” user, but you can also login as other users, which perhaps have less permission to read and edit files. If you have other developers in your team you will want to only give them access to the files they’re working on. Also note to more experienced linux users why i recommend using “root” to start: the reason is because it removes complication and makes it so new Linux users have less to learn. Eventually they’ll learn about using the “sudo” command to preface their commands. For now, guys, google what “sudo” is.

To create a group type:

# groupadd groupname

To list all user groups open up the /etc/group file:

# vim /etc/group

To list all a specific user’s groups type:

# groups username

To add a new user type:

# adduser username

To add new users to a group type (this will also create the user):

# useradd -G groupname,groupname,groupname, username

To add an already existing user to  groups type:

# usermod -a -G groupname,groupname,groupname username

To change an existing user’s primary group type:

# usermod -g groupname username

The benefit of using groups is that you can designate permissions by group, and therefore give access (or remove access) to a folder for a many users all at the same time. That’s the general idea of groups in programming in genera--it allows you to do less work by making the code you write function on behalf of a group. Then you simply need a mechanism to assign users to groups. Above are the standard user grouping mechanisms of Linux.

To update your Ubuntu installation, type:

# apt-get update

To install an application (as you saw in the server Setup tutorials) type:

# apt-get install app-name

e.g:

# apt-get install lamp-server^

To backup and restore MySQL databases use the following commands. First backup:

# mysqldump -u user_name -pYourPassword database_name > backup-file.sql

That will log you into your MySQL application (aided by a complementary application called “mysqldump”) and make a backup of the database called “database_name” and save it in a file called “backup-file.sql” in your current working directory.

Now here’s how you restore that backup:

mysql -u user_name -pYourPassword database_name  < backup-file.sql

That will log you directly into MySQL and immediately restore the contents of “backup-file.sql” to the database named “database_name”.

One key gotcha about these commands which fooled me the first (and second and probably third) times I used them was that the “-p” parameter has the password attached to it with no space in between like the “-u” username parameter.

Another cool feature I’ll just describe now is you can actually log into remote databases on a different server and restore their contents into your own database on your server. For example:

mysqldump -u remote_user_name -pRemotePassword -h remoteserver.com databasename | mysql -u local_user_name -pLocalPassword -C new_database_name

That will make a backup on the remote server and then “pipe” the results of that command via the “|” symbol into a second command, specifically the mysql command and create a new database and fill it with the results taken from the remote server.

Piping one command into another FYI is a key tool to use at the Linux command line. All these commands have output, and if that output is suitable as input to another command, just put a pipe in between. You can continue that process of “piping” one command to another as long as makes sense for what you’re trying to accomplish. You can also use an arrow (“>”) to pass any output to a text file or use the double arrow (“>>”) to append the text output at the end of the file without replacing what’s already there. That’s very useful for tracking the results of your commands.

LINUX COMMANDS 3 - SHELL SCRIPTING (Bash)

The final lesson I’d like to teach in the Linux Commands section is an explanation of what “shell scripts” are. Shell scripts are simple scripts you can make that have multiple commands in them. Then you can just execute the shell script and all the commands written it will execute without you have to typing them one after another. You do this coding in a simple language called “BASH,” which is the language the Ubuntu shell uses. But for basic scripts you don’t really need to know any bash. You could write something like:


#!/bin/sh

cd /var/log

rm log-file-name1

rm log-file-name2

rm log-file-name3

The first line is just required for the script to work. The #! symbols together are called “shebang” and basically are a signifier that the following is a bash a script. Don’t worry about it much yet.

The next thing to think is: “Crap, I could trigger this script (or any other script) via a cron job” and have it do routine cleanup for me--in this case remove old log files.

So that’s an example of the power of shell scripting. There’s obviously a lot more you can do. For scripts that deal with your application’s database, you probably just want to write a PHP script using Yii’s “console application” tools, but for scripts that mainly deal in Linux commands, you definitely want to write a bash script.

HTML/CSS 1 - INTRODUCTION TO HTML ELEMENTS

In this tutorial I’m going to teach you how to learn HTML. You’re going to learn it mainly from w3schools:

http://www.w3schools.com/html/default.asp

You’re also going to have to study their CSS tutorials:

http://www.w3schools.com/css/default.asp

So what does CSS have to do with HTML exactly? CSS is all about styling the content of your page, i.e. it’s colors, placement/position, fonts, borders, etc. HTML is all about the actual content on the page. HTML without CSS generally will appear very plain and stacked on top of each other. CSS allows you to build columns and blocks on the same line. It’s biggest strength is therefore helping you to position your HTML in pretty structures.

So what’s great about the w3schools HTML & CSS tutorials it they have a tool to test your HTML/CSS right there. You can make a change and click a button and see what effect it has immediately.

So on the w3schools site go through the links in the left column, top to bottom, studying each tutorial in order and whenever you are presented with an option to test something out, do it. You will arrive at an editor like this one:

http://www.w3schools.com/html/tryit.asp?filename=tryhtml_intro

For example, in that window, you will see this:

<html>

<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>

</html>

Try adding the following line after the line with the <h1> “element”:

<h2>My Sub-heading</h2>

Basically in html, u wrap your text content in "elements.” An element itself is made of up an "opening tag", e.g: <h1> and a "closing tag", e.g: </h1> . The closing tag is the same as the opening tag except it has a forward slash in front of the name of the type of element. Often people confuse the definition of a “tag” and an “element.” An element is the opening and closing tags and the content in between. A tag is just the beginning keyword or the ending keyword, and of course is wrapped in “< >”. Tags themselves are just a short keyword wrapped in those arrows. There are many keywords you’ll have to learn, but you’ll find that to be the easiest part. Don’t worry so much about the tag type/name. Really the way to think about it as if they all have the same name. The only difference is some provide built-in styling features that style the content in between the tags in different ways, usually in how it’s placed. In CSS you can also refer to these tags to style only elements of a certain tag type.

Generally HTML is just a bunch of nodes/blocks written on a page like this. You can also put them inside each other, for example:

<div>

   <h1>Title</h1>

</div>

Here the <h1> element is “nested” within the <div> element. Think of it like a tree, like an “outline” in school. When viewing various tools examine HTML (such as Firebug in Firefox and Inspecter in Chrome and Safari) you can expand and collapse these nodes, e.g. hide all the sub nodes nested within a parent node. This allows you to quickly browse through HTML code. It’s similar to collapsing/expanding sub-folders in a file/folder browser on your desktop computer.

The "div" tag is one of the most common tags you will use. It’s just a generic tag for dividing and grouping blocks of content. I assume it stands for "divider." Anyway, just know that you’ll end up with is a tree of tags nested within each other.

HTML/CSS 2 - INTRODUCTION TO CSS SELECTORS

First off “CSS” stands for “Cascading Style Sheets.” The main idea is you can write “sheets” of code just for styling that’s separate from the HTML content. Imagine you have a bunch of content on a page. You have a <div> tag that groups a block of content like this:

<div>

   <h1>Title</h1>

   <h2>Sub Heading</h2>

   <p>Paragraph of content in an article for example...</p>

</div>

To stylize this, you can specify neatly in code elsewhere the following:

div  {border-style: dotted;}

div p {color: blue;}

h1 {font-size: 18px;}

The beauty of CSS are these “selectors.” The selectors are the parts before the opening curly brace. They let you select the content on the page and refer to it in order to apply styles to them. This is a great thing because it separates styling code from content code, and the result is 2 places where 2 different types of code is and they are therefore more concise and easier to read. The messier way to code this is:

<div style=”border-style: dotted;”>

   <h1 style=”font-size: 18px;”>Title</h1>

   <h2>Sub Heading</h2>

   <p style=”color: blue;”>Paragraph of content in an article for example...</p>

</div>

See how the content-centric HTML code is now busier. It makes it harder to read the CSS styling code and the HTML content code. With the code in 2 places as in the previous example it’s easier to read each set of code. The benefit is also that you can write CSS that will affect more than just one block of code. All <div> elements and all <p> elements within <div> elements and all <h1> elements on the page will have the same CSS styles applied to it, and yet you only had to write that CSS once! So that means even less code. If you did it the “inline” way above, you would have to re-write the same CSS rules (more technically called “properties” and “values” in multiple places. Note: something like “border-style” is called a “property” and “dotted” is that property’s “value.”

HTML/CSS 3 - MORE ON CSS SELECTORS

There are several other very useful must-know tools in CSS. Specifically, these are more selectors, but of a slight different flavor. You can specify rules like this:

.myText {color: blue; ont-size: 18px;}

#coolStyle {font-weight: bold; color: red;}

<div>

   <p class=”myText” >Paragraph of content in an article for example...</p>

   <p class=”myText” >Paragraph of content in an article for example...</p>        

   <p class=”myText” >Paragraph of content in an article for example...and <span id=”coolStyle”>something cool</span></p>

</div>

So the 4 words/characters to notice above are:

Basically the period and sharp symbol are CSS hooks that connect to respectively to their HTML counterparts, the “class” and “id” attributes. “Attributes” by the way are extra pieces of information which you put within opening HTML tags. The “style” attribute you previously saw to supply “inline styles” was another type of attribute. So the idea is that the above <p> elements have the styling provided by the .myText selector, and the <span> element has the #coolStyle style supplied.

You use classes when you want styles to be applied to multiple elements when you can easily refer to them (i.e. select them) with simple element-named selectors, such as the ones you saw in the last CSS tutorial. For example:

.myText {color: blue; font-size: 18px;}

would apply to all <div> elements on the page, and we only want to apply that style to some divs. That’s when you use class selectors.

You use ID selectors when you want the style to only apply to one element on the page. Think of ID selectors as a way to give an element a unique identification name, i.e. “ID.”

HTML/CSS 4 - SUMMARY OF HTML & CSS TERMS

I’m going to finish the HTML/CSS section of our tutorials with a description of the main terms you learned:

1) CSS - Cascading Style Sheets

2) Selector - a CSS directive that refers to an HTML element or multiple elements

3) Element - an opening and closing HTML tag and the content in between

4) Tag - the actual text between < > as either an opening or closing tag

5) ID - identifier for a unique HTML element whose selector is a sharp symbol

6) Class - a custom selector beginning with a period that allows you to select all HTML elements on the page that have a matching class attribute whose value has the same name as what follows the period

7) Attribute - a text string within an opening tag whose value follows an equal sign and is enclosed in quotations; generally peaking, it further defines the behavior of the element.

Ultimately, the main concepts of HTML & CSS are very easy to grasp, and these tutorials sum them up. It becomes more challenging when you put it into practice and realize your page doesn’t always behave the way you’d expect, especially once you start checking it in all browsers and realize different browsers render the page differently. There are a lot of nuances with CSS especially in terms of how the page behaves. There are also a lot of CSS properties to learn, with some like the “float” property doing some unique things that take a while to get the hang of. That said, the basic syntax is pretty much summarized above. If you can get this, you should just start coding some HTML pages, and try out different CSS properties you learn about on w3schools:

http://www.w3schools.com/css/ .

Try them all until you see what’s possible. The most challenging part will be positioning, not things like colors and borders and fonts. Good luck!

JAVASCRIPT/JQUERY 1 - WHAT IS JAVASCRIPT?

So if I was to ask you what the language of the browser is what would you say? You may be tempted to say HTML, right? Well, the real answer is Javascript. HTML is a markup language, but it’s hardly a language that any self-respecting developer would call a “language.” I won’t get into the exact definition of Javascript, which includes terms like “prototype-based” and “object oriented,” etc, because you can read it here: http://en.wikipedia.org/wiki/JavaScript . But the main idea is that you can implement more complex programming structures than markup, e.g. loops, if/else logic, variables, and a lot more. You can even generate HTML on to the page without having to code traditional HTML.

So in short, Javascript is the “client side scripting” language of the browser. The reason it’s called “client side” is because your browser is a client of your server that serves the website. PHP is on the server side and Javascript is on the client side.

The main things you will use Javascript for are AJAX requests to the server, dynamically updating the page without a page refresh (sometimes in combination with AJAX, and sometimes not), animation and generally fancy interactions that make your web app feel more responsive like a desktop application. To make a Web 2.0 app’s interface and user experience sing it will all be thanks to Javascript.

Some technical notes to know are that Javascript’s syntax is influenced by C like PHP is, which is why I think PHP is a great first language to learn. Basically you’ll be learning two similar languages and have a lot of preparation for learning C, which is basically the grand father of modern programming and still very relevant. Cooler server side scripting languages of the day like Ruby and Python are a lot less like C. Therefore learning PHP and Javascript is a great place to start. They’ll make it way easier to Learn C and C++ when the time comes, as well as Java. And by that time Ruby and Python will be no-brainers.

Another technical thing to note is that Javascript basically knows everything going on in a web page. It has access to all the HTML on the page, all the information the browser provides such as its width and height, the URL being accessed, etc. Javascript has hooks into all the information about the current web page.

JAVASCRIPT/JQUERY 2 - INTRODUCTION TO JQUERY

As is the style of these tutorials, we’re going to jump you to productivity immediately. So rather than learn all the ins and outs of Javascript--and basically waste time--we’re going to look at a framework built on top of it that makes it a lot easier: jQuery. jQuery is the most popular, most maintained, and basically most advanced Javascript framework.

Since Javascript was very much like PHP in its basic syntax, the way I learned javascript and jQuery was by installing ready-made jQuery plugins, modifying them a bit, and then writing my own jQuery code. After that I went back and learned a little bit more about Javascript to really understand what was going on. Javascript does have some unique and powerful aspects that won’t be clear at the beginning as it’s quite different from a classical language like PHP, but jQuery makes it so you don’t have to know them.

Ok, so the first thing to note is that jQuery shares a lot in common with CSS, specifically selectors. Understanding selectors, which you should already by now if you read the CSS tutorials, is the crux of mastering PHP. jQuery has its own format for writing selectors. And more importantly, it lets you do more with these selectors than just style elements (though you can do that too): you can trigger events when your selected elements are clicked for example, and you can move a selected element across the page. We’ll start with these two examples.

Firstly, for jQuery to work, you have to embed it on your page. You can simply add the following line within your <head> element:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">

</script>

That will load the jQuery framework code into all browsers viewing your website. It will load the code from google’s servers, and they’ll pay for its hosting.

After that’s installed you can write jQuery code within <script> tags anywhere on your page.

Let’s cover some jQuery selectors:

Capiche. Therefore, here’s how you would do what you saw can be done in CSS with jQuery:

$(“.photo”).css(‘color’, ‘blue’);

That’s the equivalent of:

.photo {color: blue;}

Capiche. Not so difficult. Now you’re probably asking why do I need jQuery to do this when CSS can? Well obviously because you can do a lot more. Here we’re just building on similarties between the new material I’m teaching you and the CSS stuff you already know.

Let’s make it so when you click any elements with class “photo” they trigger a simple alert on the page that says “you clicked me!”:

$(“.photo”).click(function() {

        alert(“you clicked me!”);

});

So here we obviously “selected” all elements with class photo, and then called the click() function provided by jQuery, and then told it to call the function we passed into the click() function when the actual click is performed. There are 2 things to note here:

1) that jQuery selectors are actually objects, and have methods, which are separated with a period (rather than “->” like in PHP). Once you have one of these objects--usually built with a selector like this--you can call methods like click() to trigger all the event-driven stuff that CSS selectors can’t do.

2) the click() function is passed a parameter in the form of a function that will be called at a later point in time.

In this case that function parameter simply triggers the built-in browser function, alert(). The parameter we passed to the click() function is actually called an “anonymous function,” which means it does not have a name. In PHP you don’t use them much, but in Javascript and jQuery, you use them non-stop. The idea is that the code doesn’t really need a name because you’re not going to use it any other places. If you were, you could write this:

$(“.photo”).click(alertUser);

function alertUser() {

        alert(“you clicked me!”);

}

So does that make it clear how click() is really a function passed another function as a parameter. That relatively large block of code called an “anonymous” function is really just a big parameter passed to the click() function. What I’m trying to point out is simply that alertUser as shown in the first line above is a parameter, and that it’s the same as the anonymous function from the first example. This is a key concept to get.

JAVASCRIPT/JQUERY 3 - ANIMATION WITH JQUERY

Animation is often one of the most intriguing things about client side coders that new Javascript/jQuery developers always want to jump to. So lets do it.

CSS:

.myDiv {position: relative; left: 10px; width:100px; height: 25px; font-size: 12px;}

HTML:

<div class=”myDiv” />Some text...</div>

JQUERY:
$(".myDiv").animate({

            left: 500,

           fontSize: 36

          }, 5000, function() {

            alert("animation is complete!")

});


So basically what that does is move “.myDiv” by 500 pixels from the left. “left” is a standard CSS positioning property. Notice that myDiv is positioned 10 pixels from the left in the initial CSS rules. And the font size grows from 12px to 36px.

So obviously the animate() method is doing all the work here. It’s applied to the elements selected by the $(“.myDiv”) selector, which in this case is just one element, but it could move multiple elements at the same time. It receives several parameters which configures exactly how it will animate. The first parameter is a list of CSS properties to “tween” style animate from their current settings to what’s written in here.

The “5000” in the second parameter saying how long the animation should take to move those 490 pixels (i.e. from 10 pixels from the left to 500 pixels from the left).

The 3rd parameter is a function that is called at the end of the animation, which in this case will simply alert you that the “animation is complete!”

Now that’s the end of the tutorial, but lets look at how all the components truly look on a web page. I left out some required syntax that is really easy to remember--because it’s required and you’ll use it a lot--but wasn’t conducive to learning the main topics. Often when learning programming, they’ll flood you with tons of syntax and then get to the main topics, and it’s hard to know what you should be focusing on...So now that you got the main concepts, let’s look at the required syntax this is missing:

<html>

<head>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"> </script>

<style type="text/css">

.myDiv {position: relative; left: 10px; width:100px; height: 25px; font-size: 12px;}

</style>

</head>

<body>

<div class="myDiv">Some text...</div>

<script type="text/javascript">

$(document).ready(function() {

        $(".myDiv").animate({

            left: 500,

            fontSize: 36

          }, 5000, function() {

            alert("animation is complete!")

        });

});

</script>

</body>

</html>

So notice the <script> tags that wrap the jQuery, and that also embed the jQuery framework at the top. Notice how the CSS is similarly wrapped, but in <style> elements. And notice how the page is wrapped in <html> tags, and how it’s separated into 2 parts: <head> and <body>. The <head> is where you declare a bunch of meta data and generally where you enter helper tools like the jQuery framework etc.

JAVASCRIPT/JQUERY 4 - EMBEDDING JQUERY PLUGINS

So as I mentioned my first forays into the world of jQuery included embedding copy/paste jQuery plugins. A jQuery plugin is basically 3 parts:

1) PLUGIN LIBRARY CODE - a mini sort of framework that you embed into your page similar to how you embed the entire jQuery library. You won’t even need to look at this code--that’s the whole point. You don’t have to worry about its complexities.

2) THE HTML - corresponding HTML that the jQuery plugin controls. So if this was a slideshow plugin, here would be some HTML that lists photos on a page. The jQuery plugin will do something like hide all but one at a time, and transition to the other photos by unhiding and hiding them consecutively to create the slideshow effect.

3) JQUERY CLIENT CONFIGURATION CODE - a bit of simple jQuery you embed on the page with configurable properties that let you configure how the plugin works. For example, if the plugin is a slideshow, you can configure the time between transitions.

For our example, we’ll use a slideshow plugin we at FaceySpacey recently used on http://www.CrimeTV.com:

http://nicolahibbert.com/demo/liteAccordion/

Go to that page really quickly and examine it. It’s a quick tutorial on how to install and configure that tutorial with a demo of the result you will get at the top. That’s how all these jQuery plugins come--i.e. they come with a demo and tutorial on a page or two. The idea is you can easily grasp it and implement it by copying how the demo uses it.

Let’s examine their code and pinpoint the 3 aspects highlighted above.

1) PLUGIN LIBRARY CODE

<head>

    <link rel="stylesheet" href="liteAccordion.css">

</head>

<body>

    ... <!-- Before the closing body tag -->

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

    <script src="liteaccordion.jquery.js"></script>

</body>

2) THE HTML

<div class="myAccordion">

    <ol>

        <li>

            <h2><span>Slide One</span></h2>

            <div></div>

        </li>

        <li>

            <h2><span>Slide Two</span></h2>

            <div></div>

        </li>

        <li>

            <h2><span>Slide Three</span></h2>

            <div></div>

        </li>

    </ol>

</div>

3) JQUERY CLIENT CONFIGURATION CODE

<script>

    $('.myAccordion').liteAccordion({

                slideSpeed : 800,

                containerWidth : 960,

                autoPlay : true

});

</script>

So let’s start with #1 and #2 as they are the least verbose. #1 is just embedding the plugin library code:

<script src="liteaccordion.jquery.js"></script>

That points to a place on your server where the code that does all the heavy lifting that you don’t need to worry about.

Then the configuration code in #3 is simply calling the liteAccordion() method that the library code provides on a standard jQuery object built from a selector that selects an element in the HTML from #2, i.e. the div with class “myAccordion”. The liteAccordion() method takes a block of configuration settings (an “object map”) as its single parameter, and obviously you can see that they do things like adjust the “slideSpeed” and set it to 800, etc.

So now if we go back to #2, the HTML, and look at the markup there you will see that the main div containing everything has the class “myAccordion”. Within that div you will see repeating similar HTML structures. These are the panels in the accordion. The overarching idea is that the plugin will know what to do if you structure your code precisely like this. You can put whatever content (i.e. text) in it that you want, but the elements need to be nested precisely as they are above. And that’s it.

You don’t need to know much more except to copy the markup and replace it with your own text (and images, e.g. when dealing with slideshow plugins), then call the plugin method on the parent element that contains the structured markup, and finally pass to that method some configurations of your own, such as the speed with which the accordion should transition. And bingo! You’re done.

Plugins are a great way for beginning web developers to breath life into their pages. You’re going to want to google things like “jquery slideshow plugin” or “jquery accordion plugin” etc, and you’ll see that there are tons of plugins. More specifically you will see that tons of blogs have compiled lists comparing the top plugins for the given interface you’re trying to build. Here’s an example:

http://slodive.com/freebies/best-jquery-slideshow-gallery-plugins/ . Go there and find your favorite and try to make it work on a web page immediately. Just create a basic text file with the extension “.html” and copy/paste their demos properly and then open it in your browser to see. Don’t waste time before you get one of these to work and see how easy it is. Good luck!

SPECCING 1 - OVERVIEW OF HOW WE SPEC AT FACEYSPACEY

There are several schools of thought when it comes to how much you pre-plan your application and how much your developers develop it with agility, i.e. according to so-called “agile” practices. Our take is that “Agile” has been misinterpreted by many a failed startup as an excuse to operate without a proper plan.

However it goes deeper than that: we believe there are different best practices depending on the scenario. If you’re a funded startup (i.e. with funding in the millions), you have the luxury of refining an iterative process where you explore what you want to develop in small steps. You also have more experienced developers that often have worked together who have already mastered their iterative process. For new startups, this is a costly phase where you figure out your development process. So if you only have $50k-150k for your project, you’re in a completely different boat, and you simply cannot afford that. You have to operate completely differently. We believe it boils down to 1 thing you absolutely must do differently: completely plan what you will get for your $50-150k. This means you means you must know exactly what you plan to launch to the public in your initial offering. And this requires a greater degree of what has been often, and pejoratively, called “crystal ball” planning. This is where we excel at FaceySpacey and what we’d like to teach you. The process can of course be applied if you’re fortunate enough to be able to iterate more. It’s just being able to imagine your product properly and at a granular level.

The speccing process we’ll cover in the following tutorials includes these components:

1) Scope Optimization

2) Layouts

3) Organized Written Specs

4) Database Design

5) Application Code Design

6) Sprint Planning

SPECCING 2 - SCOPE OPTIMIZATION

Typically at Faceyspacey we keep the scope of a brand new startup small, but quite a bit larger than what you’d get with one iteration. One typical iteration wouldn’t be what you feel is suitable to launch to the public. So we’d spec the startup down to what a multi-million dollar startup might accomplish in about 10 small iterations/sprints as they figure out their product. In short, we determine the concise set of features that capture the essence of how you want to present to the public, and make sure not to waste any energy resources going farther than absolutely necessary.

So what that means you need to imagine a complete product from the beginning, but as small as absolutely possible. In the last phase of the Speccing process--the Sprint Planning phase--we’ll break up the plan into 5-10 sprints.

Ok so how do you optimize scope realistically? First you pinpoint your single value proposition you must get right. Without this working perfectly with a great user experience, you know you have nothing. So for one of our past startups, SnackSquare, that value proposition was the delivery of SMS text messages to people nearby your local store front. For this startup, I won’t lie, we actually didn’t do what I’m about to say here, which is how we’ve come to learn how important this technique of scope optimization is. So I’m going to work my way backward pinpointing our mistakes, and then summarize what we would have done differently.

First off, we imagined absolutely everything possible the startup would need. This included a way for merchants to add multiple stores, ways to add multiple coupons that could each exist at multiple stores (i.e. a many-to-many relationship), tools to track customers across multiple stores they may visit (or be near) and the different coupons they may use at different stores, and ways (i.e. entities) to represent the proximity-based connections between customers and a store when they are near it, entities to represent campaigns across all the previous entities and ultimately a lot more.

So hopefully you get the idea that we had to model a lot of real-world entities and the connections between them. We would have been a lot better off if we dropped the concept of coupons all together and even campaigns, as that was what everyone else was doing, and not central to our core value proposition of SMS delivery.

Instead, we would have simply allowed you to add stores. You wouldn’t create campaigns because it would be a given that a single global campaign was operating against all your stores. In terms of metrics, instead of tracking the performance of coupons, campaigns, stores and customers, we’d track just the aggregate performance of all your stores. We wouldn’t even let you drill down to the metrics on a store by store basis or the metrics for each customer (i.e. how many times they frequent your stores). We’d focus on aggregate system-wide stats, and make sure those text messages go out immediately when a potential customer is near your store. And we’d even let you only set one message at a time that would go out, i.e. a global campaign. We wouldn’t have done that whole thing where you can set the timeing and dates of multiple simultaneously-running campaigns. Maybe we’d let you set the dates and times, but that’s where it would end, and it would be one message that goes out.

The reason reducing the scope so much was so important was because the technology to track customers was damn complicated that we needed to put all our attention on that. We were completely at the mercy of changing/evolving APIs that were at the cutting edge of “geo” and just experimenting themselves with what data they provided. We had to track checkins on Foursquare, Facebook, and Twitter, all with various techniques tailored to each social network and how it produces geo-tagged checkins/tweets/updates with lat/lng coordinates, and as we went the APIs changed--usually for the better.

So anyway, that’s an example that should highlight how to reduce the scope for your startup. To put it in more abstract terms that summarize what we did, I’ll explain it like this:

1) FEW CODE ENTITIES -  keep the entities you have to model in code down to a bare minimum

2) PINPOINT SINGLE VALUE PROPOSITION - find your core value proposition and understand technically all that’s required to execute at a very deep level before you start. It’s really hard to go that deep into the tech specs of a project at the beginning, but if you can narrow it down to that one thing, it makes it a lot easier to go the mile in breaking down the technical ramifications.

3) ONE MAJOR INTERFACE - imagine only one key interface where all the magic happens. Don’t have 2+ sick interfaces that do lots of cool stuff. So that means you can have a bunch of standard web pages for your account info, and even a graph/analytics page. But only have one page where your end user gets his value from the application. Everything else could basically not exist.

This sort of thinking is completely in vogue right now in the “Techcrunch scene” as I like to call it, i.e. KISS (“keep it simple stupid”). And for very good reasons: it’s really hard to imagine everything you need to do to get your application to launch. You’ll save yourself a lot of heart-ache by putting your mind to doing just the minimum you need, i.e. get out that MVP (“minimal viable product”). Ingrain these acronyms in your head. It’s the only way you’ll succeed.

SPECCING 3 - INTRO TO BUILDING PAGE LAYOUTS

At FaceySpacey we produce layouts of every page of your application, and every state each page can be in. We do so in combination with a simultaneously running branding phase where each phase/aspect works off each other--we’ll talk about the importance of graphic design while speccing later. The imagining of these layouts is what we do best and the most important first step in planning your applications. It’s where you explore deep into what you’re app could and should be.

Lots of startups have to build lots of potentially useless stuff in order to see far into what your application needs to be at launch. This can lead to wasting lots of money on developing code you ultimately won’t use. So in essence you need to master being able to predict what you’re application needs to become if you plan to save time and money.

To master this skill, you need to think about it like a process rather than an end result. It’s not one set of layouts you make. Rather, it’s many sets and revisions that evolve. Like, don’t expect to do one round, or 3. Expect to be constantly evolving your layouts and learning more about your product through layouts. It’s way cheaper to learn about your product in Photoshop or Microsoft Paint than it is in code. Explore all the possibilities for how you’re app may look and function. Connect one interface to another. If you have a list of stores, create a page that lists the stores, put an edit/create button in the top right, then make the edit/create page, etc. Then on the edit/create page when you realize you must assign coupons to your stores, go make a coupon list page, and then a coupon/edit/create page, etc.

I’d like to say that if you’ve narrowed your scope well, the pages you need to create will be a small list, but the reality is that you’re both narrowing/optimizing your scope (as described in the last tutorial) while making these layouts. You’re constantly learning about what you’re product is. If this phase goes successfully, you’ll most likely have scrapped entire visions for your application, and removed many sub-concepts of each vision, etc. You may start out with one idea and totally change it to something more viable. During this phase you’ll discover your core value proposition, and when you do you’ll realize everything else that you have to scrap.

The goal is to get your application to a point where you can navigate through your screenshots and pretend like you’re using your application. No button can’t have a page missing for it, even if it leads to a modal popup. If it does, make another layout with the same page in the background, but the modal popup on top of it.

Making these layouts is really an important skill. This tutorial was an overview of the end goal you’re looking to achieve here, i.e. a navigatable set of layouts. In the following tutorials we’re going to break it down further. Stay tuned.

SPECCING 4 - FINDING INFLUENCES

Ok, so you get the idea that you have to get your layouts very precise and thorough. The next thing to know is that these layouts can’t be crappy “wireframes.” Checkout what a wireframe is: http://en.wikipedia.org/wiki/Website_wireframe . Lots of companies say they’re building wireframes to spec their product. Every time I hear that I laugh! That’s the stupidest crap ever. It’s not thorough enough. Just look at that image on the right side of that page. Notice the box with the X through it. That’s not thorough enough. For the list of attachments, what if the list of attachments doesn’t precisely fit in that box? Does the box get taller and now there are 3 boxes on the same row that are not all equal in height and therefore don’t look as good as initially imagined in this crappy wireframe? Does it get scrollbars? Is there paging in that box? This wireframe didn’t cover that information, and most don’t--and that’s just the beginning of all the sub-features your application needs to be complete.

Wireframes, whatever they are, do not go deep enough. All they are is just placing little vague components on a page that too generally represent what should go there. What you need to do is graphically design how every page will work, and then pin-point potential problems (e.g. missing paging links) and then design those in, and repeat.

So the technique I’ve pioneered--and say that because I think have--is copy/pasting elements from other applications/sites and combining them into basically a collage that represents one of the pages I’ve specced. Let me explain that further: I visit a web application that has a user interface that I like, then i click “print screen” and paste it into graphic design program, and crop out the full-featured component I need and paste it into the current layout I’m working on. That means my “wireframe components” are real components from other sites/apps.

The next thing I do is have our designer start designing what I have. Then when she makes cool components according to the branding style she’s been working on--and as I’m continuing to evolve the page--I grab her components and drop them in instead, i.e. replace what I copy/pasted from another site.

The idea is that real graphically designed components will drastically change your view/opinion of how your application should function. You’ll learn all you truly need from what other sites/apps have. And then on top of that, the graphic designer needs to get the best influences for what you want as possible. When you’re using interface components from other sites/apps, you’re inevitably picking components not just for function but because of the beauty of their style. So that means you’re also giving hints and clues to influence your designer’s direction, and therefore save time and money on the graphic design aspect.

What will ensue is a rinse & repeat process where you’re grabbing components from other sites,  while your designer is branding them in your app’s style (which is also evolving simultaneously), and then you’re replacing the components from other sites with the one your designer made. If you’re doing this correctly, you’ll have magic moments where you completely change one interface component to another one that is a lot more beautiful that accomplishes the same function. The reason this happens is because you’ll look at what your designer made and realize it didn’t work as well as you thought.

Now imagine you planned your entire application with black and white wireframes, and then you get to the end where you’re forcing your designer to design with such tight layout requirements. What will happen then is you’ll realize you need to change your whole plan because the ideal interface is something totally different, and in fact causes changes all the way down to the application server code, and of course the clientside Javascript/jQuery code. This is why you need to experiment with what you’re application will look like when it’s done very early on. It’s why you must examine how complete features turned out on other sites, and try to emulate those in all their details. It’s why you must try them out in combination with your other components and elements on the page, and see if it works in your case. What worked on another site might not actually end up working on your own site because of everything else going on in the page.

Creators of these other sites/apps ended up solving problems that there is no way for you to know you will have until you get to a phase where you’re testing your application. The only other way to think of these things is through your own experience of knowing potential problems from your past completed apps. However, if you’re new to this, you won’t have that luxury. You know how many times, I’ve seen page layouts missing paging, filtering and sorting for lists of data! Too many. Those basic things can drastically change the design of the page, and also can definitely change the inner workings of your application code. Filtering data can sometimes depend on complex relationships between the entities in your system. If you’re coders don’t know you plan to filter the data in certain ways, well, they won’t write the code to do so. I need to see a dropdown menu with a list of all the filter options! I.e. just the dropdown with the name of one filtering option in it is not enough. That’s how thorough your specs must be.

Be thorough in your layouts. Force yourself to imagine farther and farther into the features of your application until you truly can’t go any farther. Some may say this risks a never-ending stage of “analysis paralysis.” For some that will be the case. That will be the case if you’re new to this for sure. But if you’re new to this, it’s only going to get worse once you start development. And what’s worse: a costly phase of development that takes forever and possibly never completes? OR, a painfully long phase of planning that doesn’t cost you much because you’re doing it yourself? I think the answer is pretty clear. If you’re serious about your application you’ll finish the planning phase.

Honestly, it’s taken me years to get as good at speccing as I am. It’s taken me executing many products I thought I specced 100%, and realizing I didn’t to learn what I need to add to my specs next time. That’s just the reality. That’s why I recommend doing software as a business before you jump on your own startup, and of course start small when you finally do your own startup. You need to learn from your mistakes. If you’re new to this, you’ll inevitably make many mistakes. So do all you can on your own dime, and if you’re not technical, that means making specs. Send your specs to a professional to review and point out things missing. Hire FaceySpacey simply to do that. Have meetings with your developers along the way about questions they have. Borrow as much as you can from other full-featured launched applications as you can, and play off what they got right. Make these layouts your life. It’s your playground. Get quick at re-arranging them. Constantly ask yourself the questions of what’s missing and what other features I need to truly make this sing. When you know all the things it needs, then peel out as much as you can that’s not crucial, and replace them with the simplest way to patch up the hole. But lastly, if you’re new to this: do something so small and get it launched, and see all the work that goes into getting it launched, and by doing so give yourself a does of humility which will come by seeing all the things you missed in the planning phase that was ultimately needed before it could go live.

SPECCING 5 - ORGANIZED WRITTEN SPECS

Once you have the layouts, you need to write out descriptions for every interface element on each page. This is simple in itself once the layouts are produced. The harder part will be organizing the written specs in a concise non-repetitive format. Generally, the idea is to build a spreadsheet of tasks for each page. Each task is description of one feature of the product, i.e. of one user interface element.

Some times you’ll have features that exist on multiple pages, and you may end up describing the feature in the written specs associated with 2 pages. That’s fine, but in each place reference the other places. Also have a list of global overarching tasks. If there are things that are similar from page to page--for example how your forms should operate--make a spreadsheet that lists those tasks. If you have a header or sidebar that is always present, give them a sheet of tasks. After that, you should have a list of tasks specific to each page.

The next thing you do is use your project management software to create groups of tasks for these sheets. So that means each page has its own set of tasks listed in your project management software. Then you have your global groups. All this should be very product-centric, i.e. describing user experience, rather than deep technical notes. Though, in my opinion, don’t be too strict with yourself. I you are technical, and have some technical notes to add, add them. However later, your tech team will add deeper technical tasks as sub-tasks. Therefore you need to be using project management software that allows deep nesting of sub-tasks. We use FogBugz, which we’ll cover in the next tutorial.

SPECCING 6 - TASK ORGANIZATION & BUGTRACKING (Fogbugz)

As mentioned in the previous tutorials, I suggested building spreadsheets of your tasks. Specifically, I’m talking about using shared google spreadsheets. Build one spreadsheet, and add sub-sheets to it. Don’t juggle multiple spreadsheets use URLs everyone in the team has to remember. Start your project out with one spreadsheet with sub-sheets. Make the first sheet that appears in it something general, like directions of how the whole sheet is organized, for example. Also, make the spreadsheet accessible via a public URL. Don’t do the whole “share” thing where you invite people. People have different gmail accounts and google apps accounts, and won’t be able to visit the link, and will therefore visit the link less (i.e. when they’re logged into the gmail account associated with it) and in some cases never. In general, when building software, reduce as much friction as possible between accessing available documents, code, etc. And if you have multiple documents, link to them all from the first page of the master spreadsheet and tell everyone just to bookmark that sheet.

Ok, so you started with spreadsheets. I love spreadsheets because they’re very malleable. You can add new columns for new data, new sub-sheets, etc. People can write comments in the rows, and it’s a great place to collaborate with very little friction. Once you’re done however, you need to transfer these tasks to your project management software.

So on a per page basis (and per state basis), we create written specs closely attached to the layouts, and organize these feature requests in FogBugz, Joel Spolsky’s project management software. Joel Spolsky FYI is the creator of Stack Overflow, and a famous developer from Microsoft who worked on the Excel project. Anyway, the key here is that the list of tasks are coupled to their layouts, and then that FogBugz is arranged in a way to mirror this association just like the sub-sheets represented one page, or similar global tasks. Sometimes you’ll have group/sheet of tasks just for one state in a page if there’s a lot of interactivity going on.

Other shops may do more of a Bottom Up approach, where specs are written in association with the underlying data structures. That’s fine, but not yet. We find the problem with starting with that  approach in $50-150k contract projects is that our clients can’t closely associate the tasks being executed to precise features you’re looking to see. If you’re small startup, even working internally with an inhouse team, you’ll be in similar boat. For example, a database structure may be prepared and it took the developers a week to do, but you, as an end user testing the system, will have no way to associate the completed tasks to completed features you can use, and then you have no idea what you’re developers were doing during that time. In other words, you must optimize your process so at all times you know what’s going on in the form of testable features. Later in the technical speccing tutorials, I’ll describe how you’re developers should pin-point technical spikes and create the tasks according to a more bottom up approach.

So back to organizing Fogbugz. In Fogbugz, you will create what’s called an “area” and we use each area to group all the tasks in one of those sheets, i.e. that mainly correspond to pages at this point. You’ll then create a “filter” that will group tasks by Area first. This will create neat groups on the page obviously. Later on you’ll also arrange the same set of tasks in a different “filter” that groups by open, resolved and closed tasks. You will do so on a sprint by sprint basis. We’ll cover this more in later in the Sprint Planning tutorial. The overarching idea is that Fogbugz allows you to create multiple views through which you can look at your data, and again these are called “filters.” For now we’re creating a simple filter to view all your tasks nicely grouped similar to your spreadsheet.

The next thing you will do is organize the columns in the filter so that only the columns you need show. These columns are the title and description and nothing else. You want to be able to look at just the data you need to know now about the product now, not how the execution of the product is evolving with columns for things like status, etc. Later on you may add “status” back to it, but this is your master “product backlog,” as they’d call it in Scrum (http://en.wikipedia.org/wiki/Scrum_(development)), which we won’t cover now because we’re focusing on our own precise techniques, rather than the history of how we’ve borrowed stuff from other methodologies.

The last thing you want to do, which may actually deserve it’s own chapter, is you want to create a sitemap of all your pages. We use: http://writemaps.com/ . That tool will let you build a tree style sitemap and then link out to pages on the web. So what we do at FaceySpacey is upload all the layouts to the web and link to these layouts from the sitemap itself. This way you can quickly visualize the application as a whole via the sitemap, and dive deeper to see each layout if you want. Then the last touch is in each sitemap icon we also put in the link to a fogbugz filter that filters tasks just down to the tasks in the area corresponding to that page. This way you can quickly navigate from the sitemap to an individual page layout and its corresponding product tasks.

SPECCING 7 - TECH SPECCING (OVERVIEW)

Just because we focus on a Top Down approach, where the specs and “product” lead the way, does not mean we also--simultaneously--take a Bottom Up approach. The difference is that before each decision we make for the underlying architecture, we have a precise product goal in mind we’re working to achieve. A lot of developers may jump to modeling database tables and columns, and they’re corresponding PHP classes. They’ll imagine in their head features, and instead of making layouts as a way to embody them, they’ll model their ideas at the architectural level. However, we find that there is too much learn through exploring your products through layouts that this is not the right approach. You may end up with a totally different product, as previously mentioned, if you take the time to imagine it through layouts. Hopefully you will because there are so many options of what to build, and you need to be sure you’re building the right product if you’re going to follow through with it over many months while possibly spending lots of money. There’s so many factors to consider, and the best way to consider them is by looking at what you’re end users and customers will be looking at.

So in this part of our speccing process, we’ll come up with the entire database design. Then we’ll prepare empty code files for all the code we anticipate building. Lastly, we’ll pinpoint potentially problematic areas in the application, and discuss and write a plan for how we will address them when we get to them. This way the entire plan isn’t thrown off track when we find a major challenge deep in the app that changes the way tons of other stuff should have been coded, or even the way other features should have been.

One key thing here is that you don’t say to yourself that the product speccing stage is over and now it’s time for the tech speccing stage. While you should do a ton of the product speccing stage first, there should be a lot of overlap in the middle, and potentially the product speccing stage will go until the tech speccing stage is done and they’ll end at the same time. The idea is that while you’re examining the technical implications of the product you’ve planned you’ll most likely find major pitfalls that will cause major time-sinks in development time. Finding them is crucial if you have any hope of finishing your product. Plan to find out that at least one thing is too technically complex to develop that you have to go back and drastically change your product. This will happen, and if you suck it up and make the product changes, you’ll save yourself a lot of pain that would come later--even if it means you have to go back to the drawing board on layouts you have to craft and have to pay your designer to redesign the new stuff you came up with.

SPECCING 8 - TECH SPECCING (DATABASE DESIGN)

So what does the tech speccing itself look like more precisely? Well, first it’s all about designing your database. To do so, you need to find all the entities in your product, i.e. stores, users, videos, articles, coupons, campaigns, status updates, checkins, the relationship between these entities and each other, and build database tables to store their corresponding data. Then you add columns to these tables to hold that data. Modeling a database for these types of Web 2.0 applications really isn’t that difficult, especially if you’re product is specced out well before hand.

The hard part will be pinpointing special relationships between your main tables, and creating additional tables that don’t have clear names like “store” or “user.” For example, if you want to list all the users that edit an article, you’ll need an “edit” table that associates a user row with an article row and has a column for the date/time of the edit. It’s not a crazy concept to experienced developers by any means, but the point is that there will be harder to pinpoint “junction” tables like this. If you’ve kept your product to a minimum there will be very few of these. One way to know you’re doing too much is if you have too many junction tables. Junction tables fyi typically represent “many to many” relationships, i.e. where an article can have many users that edit it, and each user can edit many articles. For example with SnackSquare, we had junction tables like “CouponStore,” “CustomerMerchant,” “CustomerStore,” etc. There is ways to get around needing these junction tables. The main one is to plan a simpler product that doesn’t need to present every single metric to the end user. Junction tables often embody extra bonus info. Forget that bonus info for your initial launch.

SPECCING 9 - TECH SPECCING (APPLICATION ARCHITECTURE)

After you’ve built your database tables, in Yii (our PHP Framework of choice) you can actually just generate PHP model classes (and controllers and views) that represents that same data, but obviously in PHP.

If you’re reading this as a non-technical reader, this may get too advanced for you, but I’ll give you a quick overview. In the sort of applications these tutorials are written for (and the sort of application we build at FaceySpacey), the code is written according to an MVC (“Model View Controller”) architecture. The Yii Framework is based on this extremely popular pattern. The core concept to at least have a cursory understanding of here is that “models” represent your data in your database, “views” the templates that your web pages are based on, and “controllers” connect the whole thing together, making use of your models and triggering the display of models based on which URL your users visit.

Typically we won’t generate the controllers and views though as we have our own way of organizing them that’s a little against the Yii way, which we find allows us more flexibility and is standardized within our company.

Building/planning the technical architecture doesn’t stop however with the generation of some near empty shell model classes. What we’ll do next is group the layouts by controller and determine which pages our controllers will generate. The controllers generated by Yii’s CRUD (“CREATE, READ, UPDATE, DELETE”) generation tools will make a controller for each model. Often your app won’t need to allow users to create/edit/etc every single model (i.e. database table) you have in your system. For example, the “edit” table described in the previous tutorial doesn’t need a way for users to create, update or delete them. So for the models/tables that do have corresponding interfaces, we will however follow that Yii convention. For all the other pages, we’ll add them as empty shell “action methods” to a controller, whose name will logically represent all those pages. If you aren’t technical, this aspect of the speccing tutorial is probably going over your head. Generally speaking, the idea is just to assign the pages that you’re app will generate to specific code files, which technically in this case are called “controllers.”

We’ll then do the same for views. Again, we won’t follow the Yii way precisely. We’ll use their theming features and create all the views in a Theme, and organize the view files in a way that makes sense for them unrelated to the controller action methods that will trigger them. We’ll organize them in a way that a designer would think makes sense--since a designer will continue to work on them throughout the rest of the project. That way is specifically where similar layouts are grouped in the same folders, even if the layouts are from different areas of the application triggered by different controllers. We just find that not forcing your “view” files to match controllers makes it really easy to browse view files and jump between editing them. You do have to kind of switch gears a little more than if your views precisely paralleled your controllers, but we find that switch easy to make.

So either way, the idea up until now is we create basically empty files, title them properly, title some of the methods they contain, and arrange them according to a folder structure we plan to keep for a very long time.

The next bit is we’ll pinpoint problem areas, usually areas that require using 3rd party APIs and libraries, and stock the system with these tools so it’s there waiting for us. If we can, we’ll imagine our own client classes that use these tools, and again create and title empty files to represent them and put them in the appropriate place. Often when coding, you’ll be tempted to just stuff your models full of methods--right now is the time where we figure out our own components to build that model class methods can be clients of. So we’ll stuff our “components” and “extensions” folders with shell classes, just sitting there waiting to be flushed out as a reminder of what we need to build.

In short, your project’s file system becomes a to do list of what you have to code. That’s what this part of the tech speccing phase is all about. What this does is help developers see where everything is going to go. There are lots of decisions to be made here--for example if you’re going to bundle up part of your application into what’s called a “module” or a “widget.” So just the existence of these files are notes to developers saying how something should be coded.

Next we’ll set the configuration settings of the application so that all the 3rd party libraries are included, URLs are formatted in a beautiful way that will be consistent from the start, so the database is connected to the application, etc, etc. And then we’ll test developing a few things to make sure it all works as expected. What that means is we’ll make the application generate boring pages where all parts are used, i.e. the controllers, views and models, and make sure everything is working as expected.

If there are some particularly scary parts, developers should start working on them asap before all the final decisions for the product are sealed to make sure you will be able to do it. Basically send out some scouts into the most complex areas of the application and have them work on it as soon as you can. As I said before, there will be overlap between the product and tech speccing stage. As soon as the tech speccing stage is far enough long that you can start building the file system just described, get some developers experimenting with coding the hardest parts to make sure you’ve made some of the right decisions. You’ll inevitably find that some things take so much time to code properly that it will be a big time saver to back-track and change the product (and redesign it).

The final aspect in this phase is that we’ll create sub-tasks to the product tasks in Fogbugz. Obviously these sub-tasks (and often sub-sub tasks and so on) are of a technical nature. If there are overarching technical tasks that don’t apply to a specific product area (i.e. page) or perhaps apply to many pages, we’ll create “areas” for these “technical spikes.” This whole phase was about finding the problem areas in the technology. So when we find them, we need to document them not just through the organization of the file system, but as Fogbugz cases/tasks. In short, we’ll add all the technical tasks we can to the product tasks in fogbugz, and intertwine them in a logical way. If we can associate them directly with product tasks and pages, we will, and if not we’ll create new areas that group a set of related technical tasks.

SPECCING 10 - SPRINT PLANNING (And More on Fogbugz)

As you may recall from the Fogbugz chapter, I mentioned creating “filters” to view your tasks per sprint. This tutorial is all about those sprints. A sprint is a set of tasks you plan to get done in a given period of time. The goal behind sprints is to get to a point where each week you accomplish what you planned. That said, you will overestimate what you can get done in the beginning. That’s fine. Move the remaining tasks to the next week’s sprint, maybe add a few new tasks, but make the sprint size smaller than the previous week’s. Sprints can be of any length. Ours are one week at a time, and that’s just how we recommend you do it. For larger applications, such as video games, a longer sprint length may make sense, but that’s not the sort of application these tutorials are written for.

Let’s talk about the value of sprints. Sprints establish predictable rhythm of execution through which you know when to expect results. The type of applications we do (to begin with at least) are medium-small applications that capture the precise minimal viable product (“MVP”) you need. Therefore, we can do our sprints in increments of week at a time, rather than larger increments common to desktop applications of yesteryear. This insures that non-technical stakeholders feel the pace at which developers are going from the start. This allows everyone to  gauge progress, and accordingly feel comfortable with the process every step of the way.

At FaceySpacey, starting on Thursday until Monday morning, our clients in conjunction with our dedicated testers test the application. By the way, teams without dedicated testers are wasting your money by having highly expensive engineers be solely responsible for testing, and waste your time by putting the responsibility completely on you, somebody just getting acquainted with the process of software development. The final thing we do here is we do not move to new features until the current features work perfectly. The reason is simple: fixing bugs later when coders are less familiar with the code at hand takes many times longer to fix than fixing it right when they first made it. Therefore, if you don’t complete tasks in the current sprint, find new related tasks, or find lots of bugs, those tasks should go into the next sprint before adding new distinct features.

Back go Fogbugz. In Fogbugz you will take all the tasks from the “product backlog” previously described and assign them to what Fogbugz calls “milestones,” which we use to represent sprints. Basically you’ll assign the first tasks you think should be done to the first milestone/sprint, and then the next set of tasks to the second sprint, and so on. You’ll do that until all the tasks in the entire product backlog are assigned to milestones. Make sure to note that most likely you’ll end up with more sprints than you originally planned as things take longer than you initially thought, and you find your developers working on a task in a following sprint that was planned to be done in the previous one. That’s fine. What we’re talking about here is getting an initial birds-eye-overview of what will follow in the development process. Specifically, you’re pinpointing the order with which you should do things. That order will change, and you’ll alter your sprints as you go, but give yourself and your team an idea of how you imagine things going from the start.

When you build these sprint filters that lists all the Fogbugz tasks (which by the way are called “cases” in Fogbugz), you’ll group the tasks by OPEN, RESOLVED or CLOSED rather than by Area. These are called “statuses” fyi. Throughout the week you’ll see tasks move between these 3 groups from open, to resolved to closed. In Fogbugz, this is like a vertical Kanban chart. If you don’t know what a Kanban chart is, check this out: http://www.infoq.com/articles/agile-kanban-boards . It’s a way to visualize tasks go through their sequential stages from being started to completed. At FaceySpacey we find this to be a key motivational tool and tool to help us focus.

Back to how to build these sprint filters. Now, since tasks aren’t grouped by area anymore, you will need to add a column with the area so you know what part of the application the task has to do with. If your team is using the time tracking tools (which are used to generate graphs that predict when things will be completed), you’ll also want to add a column that states the time elapsed on the task. This requires that your developers record how long they work on each task. It takes a lot of discipline within a team to do this. Luckily since you’ve been using the sub-tasking feature previously mentioned, a developer can simply state how long the overall task took, like at the end of the week. Fogbugz has great algorithms to make estimates on when things will be done based on past performance. So any data here provided your developers is better than none and enough for Fogbugz to produce some pretty--and useful--graphs.

The last 2 columns to add to this filter are one for which developer each task is assigned to, and an order column provided by the “backlog” plugin. Basically you can set the order developers should do each task.

Fogbugz offers a lot of functionality, but I find the most important functionality is just how flexible its filter system is in how it allows you to re-organize the same tasks in as many different views as you want. For example, I often list tasks in a filter that groups them by developer so I can quickly see what each developer has.

Another trick I intentionally didn’t mention above is I actually create fake users for “RESOLVED” and “SPRINT BACKLOG” in order to make the vertical Kanban chart. The reason is this: the “OPEN” status is embodied by being assigned to a developer. So therefore the groups in the filter described above have the names of developers at the top, and then when each developer resolves a task the task all goes to the same “RESOLVED” group. Before a developer starts working on a task, the task is stored in the “SPRINT BACKLOG” group. And of course after the task/case is tested, it’s sent to the CLOSED group. So the trick here is that we’re user real and fake users to make the groups, and building the filter so that users are chosen for how to group the tasks. The result is that throughout the week you can watch the tasks move from the top of the page to the bottom as they go from each group to the next, and at the top there is little mini groups for each specific developer, rather than all the tasks grouped together. You could add a “developer” column to the task list, but I find visually this grouping very effective.

HIRING 1 - INTRODUCTION TO OUTSOURCING

At FaceySpacey we obviously are “outsourced” to all the time by startups. We too do a lot of sub-contracting as well for areas that are not our specialty. So we know a thing or two about how to outsource a job properly. Before I became a coder, the skill of outsourcing was one of the 2 biggest skills I prided myself of (the other was speccing). Before I was a coder, I basically had to outsource everything, especially before we had some in-house developers. So I built a formula.

The formula has been two-fold:

1) Know what you want (i.e. spec/plan your product deeply)

2) Hire the best team you can for your money

In the Speccing tutorials we cover point one at great length. So we only need cover point number two here.

Before we cover techniques to finding the best team and making sure they succeed at building your product, let’s discuss the reasons you’re outsourcing to begin with.

In an ideal world you’d build your startup with your own in-house team. Period. If you think otherwise is the right idea, all these tutorials are too advanced for you and you shouldn’t be building a Web 2.0 startup. If you’re McDonald’s and are fine paying the fees of a top-notch firm to execute some side-project initiate, sure. If you’re a small company needs to put a web “shingle” up, fine. However if you’re serious about making a successful startup and even getting it to launch, you need to understand that the ideal way to roll would be to have your own in-house team.

So that all said, the reason your outsourcing is because you can’t hire full time developers and guarantee them a professional monthly wage over who knows how many months. You need to be able to hire a firm for a fixed price where you know what you’ll get for your money. You can’t afford to go through the growing pains of building a team, learning and growing your own process of working, etc.

So that said, you got basically one shot to find that perfect web development company to build your application. And once you lock in with that team, you need to make sure they succeed.

HIRING 2 - FINDING THE FIRM TO HIRE

Finding the right firm for an outsourced project is different than how you hire developers when building an in-house team. In the latter, for example, you’ll care less about the technologies they know, and more about their overall quality. For the latter, you’ll follow the process taught by Joel Spolksy (creator of Stack Overflow and Fogbugz) in his book Smart & Gets Things Done: http://www.amazon.com/Smart-Gets-Things-Done-Technical/dp/1590598385, which we also cover in one of our later Hiring tutorials. That book says you look for 2 things in a developer: A) that they’re the smart, and B) that they have a get things done attitude. The programming languages and frameworks they are skilled in is secondary since they are sharp and get things done and will learn the tools you learn quickly, and they’ll have time to do so since it’s a long-term hire. For an outsourced project, they need to be proven masters of the technologies you need. If you’re building an iPhone app, you’re looking for developers that do primarily iPhone apps. If you’re a coder and you use the Yii Framework, they need to work almost exclusively in Yii.

So if you know what technologies are involved, you know where to look. That’s the point. Browse the Yii Framework forum for example. The more granular the skill you require is, the easier it will be to pinpoint developers with those skills. Searching for Javascript developers for example will be more difficult than searching for jQuery developers. Overall, the point is that developers congregate in certain places related to the technologies they’re using. So I’m not saying search oDesk or Elance for people that use Yii. Go to the Yii Forum and find guys that make tons of posts and are clearly very passionate about Yii.

The next thing to note is you really want a firm that’s already a firm, not just one guy that brings on another one or two guys. You want to hire a firm with a web presence and reputation to maintain. You need to be able to pinpoint where their reputation specifically is kept: i.e. on Stack Overflow, Elance, oDesk, and with past important clients. You’re a small new company with X amount of dollars under $150k. You need to know that the firm you’re going to hire will take your project extremely seriously. They need to be looking forward to adding your completed project to their portfolio.

The next thing you do is you produce as big of a list as you can of all the prospective firms you would like to possibly hire. For one of our projects, ThirstyVIP, we found a list of thousands of iPhone developers on twitter, i.e. we found their twitter URLs. We visited them all, and compiled a list of all the URLs to their sites/blogs. And then continued to narrow the list down based on what we liked on their site. We also found lists on the web of a bunch of iPhone developers. Lists do exist for all sorts of programming specialities. Find them all, and filter them down to your own list. This process could end up taking a few weeks. Just do it. Don’t even bother contacting them all until you have the list.

Once you have your filtered list, build a little micro-site to represent your RFP (“Request For Proposal”). If you don’t know what an RFP is, learn now: http://en.wikipedia.org/wiki/Request_for_proposal . It’s basically a document to potential developers describing what you want and describing your individual hiring process. For ThirstyVIP, we built an entire site with our entire project’s spec on it. Yes, we publicly put it out there because we knew how important finding the right team was and that if we didn’t we would never get a project completed anyway--i.e. we weren’t worried about the project concept being stolen because we realized there would be nothing to steal if we didn’t get the right team to take it to completion. We added a form to the site through which firms could supply their bid, and information about themselves, and emailed out a link to this site to hundreds of potential firms. That’s how serious you have to be. We even made the first page of the site have a video showing all the pages of the app (which we got designed first), with a voice-over explaining the functionality. And of course the product and tech specs were on point to the T. What this did was 2 things: A) help us get the lowest price, and B) insure the developers themselves don’t put themselves in a bad situation because they underestimated the project and therefore can’t complete it.

Basically, there are tons of firms out there. You need to put your mind to finding the best one. Take your time. Take 2 months if you have to. Take more. You only have $50-150k to get your one shot of making your dream come true. You’re not a coder. You need to bank on the skills you do have, which is communicating with people. Talk to as many of these firms as you can, feel them all out. Don’t settle. Don’t go for the first one that works. Also since you have an RFP on a public site, they know you have a lot of options. As a result you’ll get the best price and the firm most serious about taking on your project. There are a lot of great firms out there that are just not in a good place at the time to take on a project of your size. You need a firm that just completed a large project, and really needs a new one, for example. The timing must be correct. Bad timing with a great firm equals a bad firm for you. You need a great firm with great timing to take on your project. After talking to tons of firms, you’ll feel out a lot of these nuances, and have a lot more criteria to fuel your judgement.

HIRING 3 - MANAGING YOUR NEW OUTSOURCED TEAM

So you found the team, how do you not fuck it up along the way? Yes, I used an expletive in my tutorials, which I usually refrain from doing. The reason I’m using it now is because it’s so easy to be the wrench in the machine if you’re new to this whole software development thing.

The ways you may fuck it up are:

1) changing specs, i.e. changing what you want for your product -- this is the biggest one

2) talking your developers’ ears off so they have no time to work. This is a problem because you’ll most likely undermine your confidence/trust in them, while making yourself seem less knowledgeable. If you’re not technical, you’re only going to show them all your flaws. Keep your communication concise.

3) being funky with money, i.e. changing payment milestones and terms as you go. Just don’t do this. If your team is having a hard time meeting a milestone, at the beginning be lenient with paying early if they really need it, and near the end be less lenient.

4) by not having enough milestones. Have as many as you can.

The biggest no-no is obviously changing your specs in the middle. This is obviously easier said than done, and it’s the cause of 95% of all software contracting failures. It’s so easy to happen. Save extra money in your budget for when it does happen because it doesn’t, and of course spec like a motherfucker and read our Speccing Tutorials. If it does happen, be prepared to fairly and decisively work out a new contract for the additional work. Be the the first one to bring up new costs for it. Don’t make yourself look like an ass by trying to get work for free, by framing every new feature as a bug or extension of a previous feature. When you do that, you’ll just give your developers excuses to screw you in the future by not finishing your project. Be the blueprint for morality when it comes to pricing stuff out and negotiation. You’ll get more results by giving a little (or a lot) in this area. Save aggressive pricing for larger parts of your application, and for little things allow yourself to give your developers a great price.

In general, bad pricing for your developers will always come back to you. You really should be looking to pay them more than they’re used to for the same amount of work, and just keep your product small. This way they’re happy to build it. If it turns out to take longer than they thought, they’ll have less excuses to make because they were once very happy with the pricing. So don’t be afraid to take on more than their bid for the initial pricing of the complete project. That said, make sure to get a price for the complete project at the beginning, not just the first phase. Otherwise, the latter phases will inevitably be a whole lot more expensive. The reality of it is you’re inventing something new--not just making a company site--and 9 times out of ten the project will be underestimated. You really should be building an in-house team, but you don’t have the funds for that. So in this reality, it’s just a must you lock yourself into a price for the whole thing from the beginning.

Another reality is take one eighth of your budget and build the initial launch with that. If the economics make sense, i.e. for $20k you can get to launch, do it. More often than not, since you’re building something innovative of real value, it will take at least $100k to get your initial launch product done. But again, if you can get it done for a lot cheaper, do so, and save yourself a lot of heart-ache. Still apply these techniques, and just improve upon them from phase to phase. The goal is to always get what you wanted for the amount of money you first planned, and without exhausting your developer resources until they don’t want to work with you anymore, which is a very common occurrence. So that said, don’t plan half your product for $20k. Do it at $40k then, and save yourself a $110k buffer (i.e. if you’re total budget is $150k). You need your firm working towards complete products. It’s a lot easier for them to get off the hook and therefore build a lot less and fix a lot less bugs, if all that is expected is a partial product. When they’re working for something launchable--and you need to first make it very clear that they’re working for this--they’re going to go a lot farther for you. They’ll seal up minor product misses on your part.

The point is they need to be on the hook to get a product done, not just your precise specs. What I’m saying is you gave your very thorough specs to help them, but your contract with them still needs to be “complete products.” That means they’re taking some of the product responsibility on their back. If there are disagreements of the intent of the product, you need to be fair, and able to lose at least half the battles over whether something was in the spec or not (i.e. in order to maintain their trust in you). What this will do is enforce how serious you are about holding them to completing a product, not just the great specs, which will inevitably miss a few things. You need to be disciplined in sticking to your word that you gave them to build your product, and not a different product through feature requests you added. In doing so, they’ll honor their word to complete your product, and patch a bunch of product holes.

The last thing you must do is make the team you hire find do their own speccing of the product before you hire them to build it. You should pay them for this pre-phase. This phase includes them internally speccing your project more deeply at a technical level, finding product holes, and getting answers from you for what to do to solve these holes. It’s your last time to make sure your plan for what you want is complete.

You can get a price for the overall project before or after this. If you get the price after, it may be bigger because they find that their is a bunch of stuff they didn’t think of before. If you get the price before, it will inevitably be less for the inverse reason. So depending on how tight your budget is, you choose what you want to do. If they overprice, it will mean you have longer until they start giving you shit for the project taking forever. Personally, I’ll take the quote ahead of time, and earn bonus points for giving out additional money and bonuses if things are taking longer. That will go a long way.

One of the things about developers you must know is that they’re not greedy, but need things to be fair with pinpoint accuracy. They’re programmers. They believe everything can be programmed, i.e. that there is a science to every equation. Between each other, developers have a very strict code of right and wrong because they can point out precise flaws in each other’s code. I.e. if they have a debate about some technical theory, they can actually box it out in a code, while the rest of us are left making empty statements to each other that we don’t have to prove.  This culture leads to a built-in justice system. And believe me, it will carry over into how you deal with them, even if you’re not a coder. That said, I have no problem with developers underestimating. It’s their responsibility. I can’t afford to be in an all too common bad situation where I have no extra money from a client but need to get a feature done for a client because he’s expecting it and also doesn’t have an extra money. In the layer cake of contracting that I’m in, I’m at the top and therefore deal with the least technical of clients. Therefore, I’m going to get more product blunders on the part of my client where they forgot to make it clear that they really needed a feature, and truly without it their product isn’t launchable. However, developers I hire are lower down the layer cake. They’re receiving detailed specs from me, and are on the hook for less such bonuses to complete a product. So therefore, because I do provide such detailed specs, I don’t need baby developers I hire if I think they’re underestimating themselves. I feel completely justified in that. However, I will add bonuses to ease the pain if things get difficult along the way. This is how I stay in equilibrium in this cut-throat justice system between developers. In short, my clients above me in the layer cake will expect more extras missed in the spec and pay more, but developers I hire will give less extras and I’ll pay less. Of course there is a markup too, but I’m talking as if that’s not part of the equation, i.e. like when you remove inflation from economics calculations.

All in all, money is a very important part in dealing with your developers. Be on point with it as you things you missed in the spec come up. Prepare for that as much as possible by speccing like no other. Save extra money in the bank if you can’t. And build tight relationships with your guys. Not being a doosh bag is currency!

HIRING 4 - OFFSHORING

Many of you are probably wondering specifically about “offshoring.” The previous hiring tutorials specifically didn’t differentiate between “outsourcing” and the flavor of outsourcing known as “offshoring.” Now we’ll cover offshoring.

Let me say this: offshoring is absolutely perfect for coders that need small bits of help. Assign the offshore developer you’ve hired to a small task, and see if he executes to your liking, and gradually increase the size of the tasks you give him. You’re a coder, so you can monitor and understand every line of code he/she writes. Given the cost benefits and the sheer number of developers you have access to when you open yourself up to the world hiring market, it’s a no-brainer. You’ll find someone that suits your needs. In all honesty, there are tons of fantastic developers outside of the United States. And the economics do work. They can work very very well.

However, it’s no secret that developers not smack-dab in the middle of Silicon Valley don’t have the product common sense--if you will--that ones from the US are more likely to have. It’s very common for coders to not have the product common sense you do in general, especially when you’re product takes the insider knowledge that you have from doing business in your niche. That’s always going to be given. So couple that with the fact that a lot of these great developers come from countries where only a handful of their friends have iPhones, etc. In short, you’re going to be in for a painful awakening when you hand a team of these developers your spec, agree to a large fixed price for your project to be executed over several months, and they end up misunderstanding many things along the way. This is a story that’s been told too many times.

So we’ve already covered how important it is to spec deeply, how to find a great team, and generally how to manage them after you hire them. Let’s now discuss some techniques specific to managing offshore teams if you’re not a coder yourself.

The best way to do it is to make software development your business. I.e. you can be a product guy that project manages, and hires offshore teams. So if you can make software development your business and you have clients you do websites for, what you’re looking to do is basically lock down your own exclusive team and evolve a way to work with them over time. Of course start with small projects--may do a company site for the store down the street.

The benefit of having your own exclusive team is that they cannot give up on your project in the middle. They are depending on you for the next project. So you basically eliminate the fear of having them leave you. You’ll inevitably have to overlap projects when one project takes too long and ends up being worth less more money per all the time it’s taking than originally planned. You can essentially pull somewhat of a Bernie Madoff style ponzi scheme. You’re going to have to fix it at some point. I’m not saying to doing anything imorral at all. I’m simply dealing with reality here. You may have times where you have to feed your offshore team a different project while still working on a current project to help them make sure their financial needs are met while they go the mile on the current project. If you’re smart, the additional project will be priced better. If you’re new to this business, you may use the currently half-built project to demonstrate to prospective clients what you’re capable of. I always use my newest projects to showcase my work anyway, as my newer work is always better than my last.

That said, even if software development can’t be your business, you should find other projects to give to them. You should start them on a small non-crucial project first. You should do whatever you can to show them that you’re a repeat customer. Period. Build a serious rapport with them that they know will last a long time if they do a good job. This is the technique.

If you actually do have a full time web development business or actually see yourself doing this, here’s how you lock down a team permanently:

1) find a budding camp of 2-3 developers (i.e. off odesk, or elance)

2) make sure this camp isn’t far enough long in their careers that they have their own company site.

3) be the one that helps take them over the edge to being a professional development firm, or at least be one of their first clients, or at the very least their most serious client ever.

4) don’t cramp their style--so let them have their own company they can call their own offshore

5) then make an agreement that you’ll be their exclusive client and you’ll provide all the jobs. All the problems will occur when they start working on other projects in place of yours.

6) You will need to take responsibility for their minimum financial monthly goals. Figure out what those are. And be prepared to have their back in times when your main projects are taking more time than they should (and therefore costing them more money).

7) Make sure to price everything out at a fixed price. They are offshore, not in your office. This is the only way they can will feel they have to take full responsibility for the work your sending them. You’re not Microsoft building whole offshore companies in Romania or Google doing the same in India, etc. Those companies can pay developers consistent salaries rather than do fixed price because they’re not really offshoring--Microsoft and Google are just expanding their companies to those countries and some may call that “offshoring.”

8) Have their back when things get messed up (i.e. in terms of money). Show them that you can be flexible too and you’re not out to screw them. This is a must when they hit hard times on your all-important main project and it’s harder than they expected. It’s what will make them go the mile to complete it.

9) Find one main guy offshore that leads the team, takes on all the responsibility, etc.

So that’s basically it. Let me describe building that main relationship with your offshore team lead more. You need to build an organic and tight relationship with that one lead offshore guy. One guy over there must have his ass on the line. By helping him build a company, and do things like get office space (which should be cheap where you’re offshoring too), and have status by being the boss of several guys over there, you’re already making his dream come true. Usually in these countries, their dream is to be the owner of a contracting company, not to take all the risk in building a startup like your dream is. It’s very true that people in the US are a lot more risk-averse while people in 3rd world countries have lots of doubts of what’s possible. I’ve had these discussions point blank with many offshore developers I’ve worked with, and it’s not just a myth. It’s completely the truth and they know it and admire the US for this. You need to own this fact and use the economics it produces to your advantage.

There is very few examples in their homeland of successes like Facebook, Twitter, etc. They just can’t afford to dream that high, and don’t. Therefore, the bar for the dreams they must accomplish is a lot lower, and you can basically be the one to make it happen by helping them build their little software contracting company. And again, it’s all about pinpointing one main guy that will hold down the fort. You won’t be able to have that relationship with all the developers he finds because everyone doesn’t have a business owner mentality. So that’s the point I’m trying to make--make sure the guy you find has a business owner mentality, will work weekends and do whatever it takes. You’re going to need it. In short, you need someone else to share the burden of the responsibility for completing your project with.