Feeds

100702 items (2009 unread) in 22 feeds

CNN CNN
MSNBC MSNBC
PHP PHP
Deals Deals
Tech Tech
Web Development Web Development
CNN Money CNN Money
Frugal Blogs Frugal Blogs

Nettuts+

  • Permalink for 'Why Many Developers Hate ASP.NET… and Why They’re Wrong'

    Why Many Developers Hate ASP.NET… and Why They’re Wrong

    Posted: November 29th, 2011, 8:49am MST by Jeremy McPeak

    Few platforms draw the same amount of ire as ASP.NET (or .NET in general) from the development community. While there are certainly valid criticisms of the platform (what platform doesn’t?), the majority of negativity comes from those who haven’t spent any time with .NET. Those developers typically rely on misconceptions or flat out hatred to base their opinion, and they do a disservice to others looking to learn a new technology and to the platform itself. So, let’s examine these excuses and add a dose of reality on why you shouldn’t listen to the rabble and give ASP.NET a try.

    It’s Made by Microsoft

    This is probably the #1 reason for all ASP.NET hate.

    Microsoft is a massive software corporation, and like all other corporations, they’re in business to make money. Duh, right? Unfortunately, this is probably the #1 reason for all the ASP.NET hate: it’s a Microsoft technology, and the “evil” taint still lingers over the giant in many people’s minds. I’ve always found this interesting because the other major technology companies, such as Google and Apple, are just as “evil” as Microsoft, but the zealots fans of those other companies typically turn a blind eye (or are in denial) to those “evils.” I personally think the majority of people are normal minded people. They don’t really care who makes a product as long as that product works well.

    But I’m not talking about normal people, right? Normal people don’t see a headline containing "ASP.NET" and have an automatic urge to make an inane comment. Instead, I’m talking about the developers (and geeks) that treat technology, and/or the company that creates it, as a religion. I’m not kidding—find any article or tutorial on X platform, and chances are good you’ll find comments stating “X Sucks! Y Rules!”

    It’s as if these people are on some weird crusade to defend their chosen tech/company to the hilt and bash the competition in an attempt to bring the unwashed masses into their fold.

    It’s sad that the technology = religion mindset exists. Technology is a just tool, and a real developer is going to try multiple tools in order to find the right one for the job. That’s not to say that someone cannot dislike a technology, but to echo our parents, "you don’t know you don’t like it until you try it." In order for someone to truly dislike something, that person has to try it. So don’t listen to the rabble—they haven’t tried it and haven’t formed an informed opinion. If you decide you want to try it, they’ll attempt to dissuade you by saying it costs too much.

    Misconception: It’s Expensive

    Find any article comparing ASP.NET with any other platform, and you’ll read, either in the article or in the comments, “ASP.NET costs more than [insert any other server-side tech other than ColdFusion here].” Before discussing the actual cost of something, it’s important to put the term “expensive” in context, as what is expensive for personal use can be considered cheap in a business environment. In business, there are many factors that make up the “cost” of a product. The initial price obviously needs to be considered, but the benefit of the product is also factored into the overall cost.

    If a product is $10,000, but it saves the company $1,000 a month, the purchase decision is a no brainer. But on a personal level, it would more than likely be difficult to justify the initial $10,000 cost.

    So when talking about cost, it’s important to keep things in perspective according to the context in which it will be incurred.  To keep things simple, I’m going to assume that if you’re reading this, you’re more concerned with the personal cost than the business cost (if I’m wrong with that assumption, I’ll make this very easy for you: if you have a Windows environment, ASP.NET is cheap).

    You don’t actually need Windows to develop ASP.NET apps, thanks to the Mono project.

    Let’s get the biggest cost out of the way: the Windows operating system. You don’t actually need Windows to develop ASP.NET apps, thanks to the Mono project (more on this later), but Mono typically lags behind the official .NET Framework coming out of Microsoft’s ovens. So, if you want all of the latest features and .NET-goodness, you’ll need Windows. Most OEMs (companies like Dell, HP, Acer, etc) ship their computers with Windows already installed; so, if you buy your computer from an electronics chain store like Best Buy, chances are pretty darn good that the computer will have Windows. If you’re more of a power user and build your own computers or plan on run Windows in a virtual machine, you will have to purchase a copy of Windows. An OEM version of Windows will run you anywhere from $99 to $189, depending on which version of Windows you buy. You don’t need to have Professional ($139 OEM) or Ultimate ($189 OEM), but if you’re a power user, you’ll more than likely want to opt for one of those two versions (OEM versions are cheaper than retail versions, but they are tied to the hardware you activate them on).

    Development Costs

    With that out of the way, let’s review development costs. ASP.NET development is thought to be expensive for two reasons.

    1. It’s Microsoft. They supposedly don’t give anything away for free, but that’s exactly what they do. Everything you need to develop ASP.NET applications (or .NET apps in general) can be obtained without spending a dime.

      Beginners: First, Microsoft gives away WebMatrix, a development environment targeted at beginners. It combines an integrated development environment (IDE) with a built-in web server (IIS Express) and a database engine (SQL Compact Edition). It also has tools to help users deploy their websites to a remote host.

      Advanced Users: For more advanced developers, Microsoft makes available the Express editions of Visual Studio. Like WebMatrix, these trimmed down versions of Visual Studio are free, but they offer some of the features and abilities found in the full versions of Visual Studio. The web-focused Express product is Visual Web Developer Express (VWD), and it, too, has a built-in web server. It doesn’t have a built-in database engine, but Microsoft gives away SQL Server Express, a trimmed down version of SQL Server, that you can use for development (and even some deployment situations). If you later decide you like Visual Studio and want to purchase the full version, the projects you developed with VWD can be opened with Visual Studio.

      Students: And if you’re a student, you can get lots of Microsoft software (Visual Studio Pro, Windows Server OSs, and Expression Studio to name just a few) for free through the DreamSpark program.

    2. Secondly, Windows-based hosting is thought to be mucho expensive-o. Ten years ago, that argument held some weight. Today however, you can find no shortage of reasonably priced hosting for ASP.NET. DailyRazor (the company I use) starts plans at $2/month, and you can find other hosting providers that sell their services at low prices.

    So cost isn’t really a problem, but naysayers will then say ASP.NET is only suitable for enterprise-class websites as opposed to your personal site(s).

    Misconception: It’s Horrible for Small, Personal Websites

    One only has to look at the .NET Framework’s class library to get the “this is for enterprise” feeling.

    It’s actually easy to get into the mindset that ASP.NET isn’t suited for anything but large-scale sites. Microsoft is a platform company, after all, and their products are primarily focused towards business solutions. .NET isn’t really different in that respect; it’s huge in business environments, and its foothold continues to grow as Microsoft expands new and revitalized products like Azure (Microsoft’s Cloud platform) and Windows Phone, respectively. One only has to look at the .NET Framework’s class library to get the “this is for enterprise” feeling. It’s almost as if the framework guides developers to a mindset that (ASP).NET applications needs to be highly structured masterpieces of object oriented design. A lot of .NET is complex, and doing simple things isn’t always as simple as it should be. It sounds like I’m making the naysayer’s case, doesn’t it? I kind of am, but there two things to consider.

    Simplicity

    First, Microsoft wants you developing on their platform, and they’ve recognized that it needs some (perhaps a lot of) simplification in order to grow. After all, PHP is as popular as it is specifically because of its simplicity, and that’s the primary reason Microsoft released WebMatrix: to offer new developers (either to .NET development or web development in general) a simplified approach to writing sites with ASP.NET.

    Not only is the all-in-one IDE easy to use, but Microsoft created a simplified API to make ASP.NET development easier and less complex.

    Multiple Approaches

    You can also build sites with the same kind of “scripting” mentality that thrives in PHP.

    Second, you don’t have to fall into the “highly structured or die” mentality. There are many approaches to ASP.NET development. If you want to create highly structured masterpieces of object oriented design, you can. But you can also build sites with the same kind of “scripting” mentality that thrives in PHP. The point is, ASP.NET development is flexible enough to fit your needs, and you can choose the development approach that best fits you.

    Oddly enough, there’s a somewhat prevalent idea that ASP.NET isn’t suitable for enterprise-class websites. o.0

    Misconception: It’s Horrible for Large, Enterprise-class Websites

    I honestly have no idea where this comes from because, as mentioned earlier, ASP.NET excels in the enterprise space. But don’t just take my word for it; let’s examine a real-world website (well, a network of websites) that run on ASP.NET.

    Have you ever heard of StackOverflow.com? You probably have, and if you haven’t, it’s a Q&A website for developers (regardless of technology). Its an invaluable resource, and one I find myself visiting quite often.

    StackOverflow is a member of the Stack Exchange Network, a network of Q&A websites for a variety of topics: servers, databases, legos, sci-fi, cars, and so on, and so on. There are currently 71 sites in the network, and it continues to grow.

    The folks at the Stack Exchange Network are pretty open about their network. Much of the code running on the site is open sourced, and they often provide information regarding the network in general. In a March 2011 blog post, Kyle Brandt provided an overview of the technology powering the Stack Exchange Network, as well as the traffic the network gets. Keep in mind this information is regarding the entire Stack Exchange Network. It gets 95 million page views a month and handles 800 HTTP requests a second, and those requests are handled by twelve (yes only twelve) Windows web servers, two MS SQL Server servers, two Linux load balancers, and two Linux caching servers (fail-over hardware is not included in that count).

    Reread those stats—I’ll wait. Phenomenal, right? It’s amazing that only twelve servers, serving many different websites, handle that amount of traffic. It’s a testament to just how good Microsoft’s server and application architecture is.

    It’s Statically Typed

    Dynamic languages rule the web. Be it on the server side, where languages like PHP, Ruby, Python, and Perl live, or in the browser with JavaScript, dynamic languages are the backbone of the web. It’s not that these languages are better, but they are quickly adopted because dynamic languages are typically easier to learn and understand than statically typed languages.

    So what we essentially end up with is a massive community of developers who have only used dynamic languages, and that community almost has an aversion to static languages.

    I fully understand the mindset. I used to be one of those people, and I understand the desire to stay within one’s comfort zone. After all, dynamic languages are lenient, and there is some comfort found in that leniency.

    Static languages have a strict type system.

    But there’s a bad side to that leniency; it is extremely easy to introduce bugs into your app if you’re not careful. You’ll typically not find that bug until runtime, and a common cause of bugs is the assignment of a different and unintended type of value to a critical variable. This is where the primary benefit of static languages comes in: type safety. Static languages have a strict type system, in that a variable can only contain one type of value (eg: a variable declared as an integer can only contain integer values; it cannot contain a string or floating point numbers). If you mistakenly assign a string to a number variable, you will immediately know of the error when you compile the code because the compiler with halt and alert you to the error.

    Type safety can also alleviate the type checking you need to perform in dynamic languages. For example, how many times have you written code like the following to ensure the data a function accepts is of the expected type:

    function add($a, $b) {
        if (is_int($a) && is_int($b)) {
            return $a + $b;
        }
    
        // throw error
    }

    This is a simple PHP function that adds two numbers together. In order to ensure predictable results, checking if the supplied values are of the appropriate type is imperative (admittedly, the type checking here isn’t complete; there are numeric types other than integer); otherwise, your app could break at unexpected times. In contrast, let’s look at the C# equivalent code:

    int add(int a, int b) {
        return a + b;
    }

    This code defines an add() method. C# is the most popular .NET language, and it is purely object oriented. There are no functions; only methods of a class. This method accepts two integer values (denoted by the int keyword before the a and b identifiers), and it returns an integer value as denoted by the int before add. Because C# is a static language, the type checking is performed by the compiler—not by you. So, if you were to call this method, pass a string as one of the arguments, like add("hello", 123), and attempt to compile the code, the compiler will stop the build process and alert you to the error. Chances are, however, you wouldn’t even try to compile the code because Visual Studio performs its own type and syntax checking; the IDE will warn you of errors before you even try to compile (see the below screenshot of Visual Studio 2010).

    Also consider that Microsoft continually updates and improves the C# language. In the first two versions of the language, you had to identify a variable’s type when declaring it like this:

    XmlDocument document = new XmlDocument();

    This code creates an instance of the XmlDocument class by declaring its type prior to the variable’s name. Admittedly, this syntax is rather cumbersome and adds far more typing, but as of C# 3.0, however, you can simply use the var keyword to define a variable, like this:

    var document = new XmlDocument();

    There are .NET-enabled versions of PHP, Ruby, Python, and PERL.

    The compiler is smart enough to infer that the document variable is an XmlDocument. This syntax sort of blurs the line between dynamic and static languages. You get simple, typeless variable declarations with the benefits of type safety… a win-win in my book.

    But if I still can’t persuade you to give C# a try, ASP.NET sites do not have to be written in C# (or even VB.NET… but who would want to do that?). There are .NET-enabled versions of PHP, Ruby, Python, and PERL (and others) that you can use to write ASP.NET sites with, and they are just as dynamic as usual thanks to the Dynamic Language Runtime, a feature of .NET 4. So while I recommend anyone picking up ASP.NET to learn C#, you don’t have to leave your comfort zone if you don’t want to (but if you do the benefits are worth it).

    It’s Compiled

    The same dynamic languages that rule the web are also interpreted, and there is a certain benefit that comes with interpreted languages. Unlike compiled environments like ASP.NET where you typically write your code, compile it, and upload it, interpreted environments let you simply write your code and upload it. The common idea being that compiled environments require an extra step in development, and that wastes time. But it really doesn’t. The compiler gives us many benefits that you just cannot get in an interpreted-language environment.

    First, the compiler checks the code and can give you warnings. Warnings are just that: a warning. It’s something you’ve done that may be a bug, but it won’t stop the compiler from compiling your code. Let’s look at the following code that would cause a warning:

    string DoSomething()
    {
        var foo = "Hello";
        var bar = "World!";
    
        return foo;
    }

    This code defines a method called DoSomething(). Its body creates two string objects, foo and bar, and foo is returned to the caller. The bar variable is not used, so the compiler would issue a warning stating that bar is assigned but its value is never used. It may be that I created bar and forgot about it, or that I ended up not needing it. But it could be the source of a bug if I forgot bar already existed and used it elsewhere in the method. The compiler brings it to my attention so that I may address it and avoid future bugs. Here’s a screenshot of what Visual Studio tells me:

    Do you want another example? Sure you do:

    void DoSomethingElse()
    {
        var foo = true;
    
        if (foo = false)
        {
            // this code will never execute
        }
    }

    In this method definition, a boolean variable, foo, and defined as true. It is then used in an if statement, where it is assigned a value of false. That may be exactly what I intended (although I would argue that I should never do that), but chances are I meant foo == false (yes, the logical not ! operator would be better here… but it doesn’t work for my example). It’s not an error, however, so the compiler will compile the code. However, it will issue a warning asking if I meant == instead of =. These are issues that I would have found an in interpreted environment, but I would have needed to run the app and test it in order to find those mistakes.

    Second, the compiler checks the code for errors. Naturally, a compiler cannot catch logic errors, but it can type check and check the code’s syntax. Although, a decent IDE will do these things for you without needing a compiler, and Visual Studio does.

    Last, you get a performance boost. Compiled code runs faster than interpreted. Admittedly, .NET isn’t a truly compiled environment. Our code is compiled into an intermediate language (IL), which is then just-in-time compiled by the .NET runtime. The IL, however, is optimized, and the .NET runtime executes it. But it’s still very fast.

    In fact, ASP.NET’s raw performance is faster than PHP’s.

    Misconception: It’s Closed

    Microsoft makes the source code for the .NET Framework available for free.

    Microsoft is a company that sells software, and they are naturally very protective of their products’ source code. So, one might think that ASP.NET (and .NET in general) is closed source, but that is not the case. Microsoft makes the source code for the .NET Framework available for free, and you can step into the code while debugging your own apps. You can even build your own personal version of the .NET Framework.

    Microsoft also gives you access to the source code of ASP.NET releases, like WebForms and MVC, via CodePlex; giving you the ability to test new features and provide feedback to the ASP.NET team. I encourage every developer using .NET to download these free resources and study them. You’ll gain a greater understanding of how it works under the hood, and you can apply that same knowledge when writing your own code.

    It’s Windows Only

    Microsoft’s openness with the .NET Framework is what helped birth the Mono project, a cross-platform version of the .NET Framework. While Mono isn’t officially supported by Microsoft, the project has been publicly acknowledged by Microsoft. Mono isn’t going away; in fact, it’s growing in popularity  Regardless of what your favorite platform, you can probably use the .NET Framework and C# to write apps for it (you can even write iOS apps with Mono!).

    It’s Not in Demand

    Lastly, it’s often espoused that ASP.NET is not in demand, and that simply is not true. Demand is somewhat subjective because different areas of the world and in the country you live have different job markets. For all intents and purposes, .NET has been the development platform for Microsoft Windows environments (both for the desktop and the web) over the past ten years.

    Most software developed for Windows uses the .NET Framework, and so there is a huge opportunity for new .NET developers to find work.

    The Mono project also factors into demand. Mono is huge, and the community is just getting bigger. With its wide breadth of OS support, you can write apps for any of the big OSs, including mobile devices. There is opportunity galore, regardless of OS!

    Conclusion

    So where does all this leave us? Well, the haters and naysayers are wrong, and ASP.NET is a technology that you should try and get to know. After all, successful developers are polyglots—able to write applications in different languages for different platforms. So give ASP.NET a try. What do you say?


  • Permalink for 'Are jQuery Users Fools?'

    Are jQuery Users Fools?

    Posted: November 27th, 2011, 3:00pm MST by Jeffrey Way

    We should get this out into the open. There seems to be a commonly held belief that jQuery users are ignorant, and, more often than not, designers. Where did this come from, and is it true?

    Roots

    The JavaScript community wasn’t nearly as vibrant and passionate as it is today.

    Let’s take a trip down memory lane; we’ll rewind the clock several years – pre jQuery days. The JavaScript world was a very different scene back then. The community wasn’t nearly as vibrant and passionate as it is today. Sure, back then, there were a few libraries, like Prototype; but they never managed to grab the regular user spotlight the way that jQuery soon would. At that time, JavaScript was a widely hated language. Sometimes, it’s easy to forget that there were times when developers refused to take the necessary time to …ya know… learn JavaScript! Instead, they’d simply copy and paste their way, hoping to keep from getting that nasty JavaScript stain on their pants.

    The DOM

    What you mean is, “I hate the DOM API.”

    What these copy and paste addicts (I was one of them) didn’t realize is that, when you say, “I hate JavaScript,” what you really mean (whether you realize it or not) is, “I hate the DOM API.” No one can be blamed for feeling that way. Especially back in those days, when even IE5 support was in effect, things could get a bit nasty. Browser implementations of the DOM were the culprit; not the JavaScript language. This is due to the fact that there really wasn’t any DOM specification. As a result, browsers sort of winged it as best as they could! We have innerHTML not because of a specification, but because the Internet Explorer team decided to just throw it in there (at which point the other browser vendors reverse engineered it, and implemented it into their own browsers). But the JavaScript language, as a whole, is solid.

    In fact, many folks, including myself, would go as far to say that, as a language, JavaScript is really quite beautiful.

    jQuery

    Around that time, jQuery entered the atmosphere, and began taking the development community by storm. While other libraries like Prototype still retained a certain level of complexity and confusion for newcomers, jQuery was ridiculously easy to grasp, thanks to the fact that everything is accessible, via the jQuery object (something that it’s, ironically, often criticized for).

    Need to apply a class? Easy; doing so is tailor made for designers. jQuery allows you to use the CSS selectors you already know to query the DOM.

    $('#container').addClass('ahh-yeah');
    

    Fun Fact: Technically, though jQuery popularized the idea of a CSS selector engine, it was largely based on work by Dean Edwards.

    And then, at some point, the timeline skewed into this alternate reality…

    It literally couldn’t be simpler. By abstracting away complex code and browser quirks, developers could get back to doing what was important: creating websites and applications.

    While jQuery’s community grew in leaps and bounds, the library, itself, also continued to mature and take shape. The world was peachy.

    And then, at some point, the timeline skewed into this alternate reality (okay, not as Doc Brown as that), where, suddenly, if you labeled yourself as a proud jQuery user, certain members of the JavaScript community would consequently feel the need to stereotype you as an ignorant “designer” (regardless of whether you were or not) – certainly not a “JavaScript Developer.” How did this happen? JavaScript developers don’t use jQuery?

    The Burden of Popularity

    Everyone has an opinion about the spotlight.

    It’s only natural that, once you reach a certain – for lack of better words – popularity, you open yourself to incredible amounts of scrutiny. Everyone has an opinion about the spotlight, it seems. For example, you’ve no doubt heard endless criticism of Catholicism. “They worship statues.” Is that the only religious body with questionable history? Surely not; but it’s the largest. The United States is one of the most powerful countries in the world. Naturally, everyone has an opinion. “Americans are ignorant and fat.” Ignore the good, and spotlight the bad.

    jQuery is the most popular JavaScript library, by a landslide. Again, everyone has an opinion. I’ve read countless criticisms – everything from what it doesn’t do, to the structure of the code base. However, perhaps the biggest criticism of jQuery comes from a simple truth: its users, as an average, are less experienced with vanilla JavaScript, when compared to, say, Mootools. While some consider this to be a downside, I honestly view it as a strength – in an odd way.

    The fact that jQuery has many less-experienced users is not its downfall; it’s a testament to its appeal.

    jQuery Users Don’t Know JavaScript!

    This is the argument you’ll hear more than any other. Again, a testament to jQuery, many people learn jQuery before vanilla JavaScript. There have been countless debates on whether this is a good thing or not. In fact, these sorts of discussions extend to all abstractions.

    • Should designers use CSS preprocessors and frameworks, like Sass and Compass, respectively, before learning the ins and outs of CSS?
    • Is it okay for a Ruby developer to use CoffeeScript without first learning JavaScript?
    • Should you use Modernizr before learning how to write a single feature test?
    • Is it okay to use CodeIgniter if you’ve only just learned PHP?

    Personally, I feel that those who demand that newcomers first learn JavaScript before moving on to jQuery are missing one thing: JavaScript and the DOM are scary! If you throw the ES5 specification at them, they’re going to have a heart attack, unless they have a real interest in becoming a JavaScript developer. Many people simply need to add a few effects to their websites. We can’t always master everything. Are they bad people for choosing their priorities? Of course not.

    JavaScript and the DOM are scary!

    Compare this to simple Math. When you first learned how to add 2 + 2, did you do it the official way? I sure didn’t; I used my fingers. I bet you did too. Though it’s a huge simplification of the issue, is jQuery not the same way? It provides new JavaScript users with a simple and exciting entry point. Do you honestly expect them to learn about closures and objects and global variables before they even learn how to do something fun? Come, come, now.

    The strict, “Learn it the right way, or you’re a fool” viewpoint is naive, and doesn’t take into account the various learning styles that we all have.

    I view jQuery as bait. Hold it over the user’s head, get them really excited by it, and then, when they feel ready, they almost always move on to learning more vanilla JavaScript.

    jQuery Users Write Poor Code

    Once again, this is a massive generalization. Some of the biggest and most influential companies in the world use jQuery. But yes, there are lots of beginners who are still in the process of learning. Oh well; it happens. Poor code exists in every language. I’ve written a good bit of it myself, I’m proud to say! The best we can do is, rather than scorn them publicly, offer advice and tips when we can. We’re all learning. Do we really need to attack some, because they have different priorities and skill-sets?

    With popularity, comes the potential for bad advice.

    jQuery managed to generate this incredibly passionate community – from the hardcore JavaScript developers down to the designers who were amazed by how easy it was to get the job done. This passion subsequently lead to countless jQuery tutorials by community members – both good and bad. While still learning jQuery (something I’m still doing), I can guarantee that I offered some terrible advice at one point or another. It’s not too dissimilar to the PHP community. With popularity, comes the potential for bad advice.

    The Ruby Community

    This sort of pointless teaching almost hurts the community.

    In the Ruby community, there’s an interesting dynamic. Tutorials are, to generalize things, written by the veterans. In other words, if you’re going to write a Ruby on Rails article or book, you should fully expect extreme scrutiny. If you don’t have a massive level of experience, don’t you dare write about it. In some ways, this is a strength. As a student, you can more easily rest assured that what you’re learning is correct. On the other hand, PHP tutorials are all over the place. Writers sometimes focus on the insignificant, and ignore the important. You’ll often find best practice PHP tutorials, which describe whether or not it’s faster to use single quotes or double quotes. Of course, this sort of pointless teaching almost hurts the community.

    What Do You Prefer?

    It’s an interesting thing, I must say. What do you prefer? A smaller, passionate base, or an incredibly popular one, consisting of all skill levels? There’s certainly pros and cons to each.

    It’s undeniable that many of us feel a need to be trail blazers. Remember when parents began signing up for Facebook? Critics widely declared that the end of Facebook was near. Once you sacrifice exclusivity for wide appeal, people instinctively begin searching for the next thing. But that didn’t happen. The same is true for jQuery. Sure, some users have moved on to more comprehensive frameworks, like Dojo. But that’s to be expected, and should be a badge of honor for jQuery. For many, the learning cycle goes like this:

    • Learn jQuery; get excited.
    • Realize that you have no clue what this refers to in different situations. Learn JavaScript, and incrementally improve your old jQuery code.
    • (Optional) Advance your skills to the point where you need a more comprehensive framework for building large applications. Begin reviewing additional tools, such as Dojo.

    Is that so bad?

    Real Deadlines

    It’s not like we’re coding in binary here, folks.

    There will always be the advocates who suggest that you shouldn’t use a library – period. Given the current state of JavaScript and the DOM, though, I honestly feel that this is bad advice – particularly for newcomers. They shouldn’t be expected to wrestle with frustrating browsers inconsistencies so early in the learning process. And, many times, abstractions are a very good thing! It’s not like we’re coding in binary here, folks. When you use jQuery, or any other popular library, you’re benefiting from countless tests, bug fixes, and the best minds in the industry.

    Now, certainly, you’re not required to use somebody else’s framework. Create your own library, if you have the ability; that works too! The goal is to:

    • Normalize browser quirks
    • Write less code
    • Benefit from as many minds as possible
    • Meet real deadlines, and get the job done

    jQuery is not “a designer’s library,” but it appeals to designers. It’s not as class-based as other libraries, but this makes the entry point for newcomers far more painless. So what we end up with is a library that helped reignite the JavaScript community. It’s simple enough to appeal to first-timers, and powerful enough to be used by the largest companies in the world. Why exactly is it being criticized again?


  • Permalink for 'Latest Web Development Jobs at FreelanceSwitch'

    Latest Web Development Jobs at FreelanceSwitch

    Posted: November 25th, 2011, 11:15am MST by David Appleyard

    Looking for a new web development job? The FreelanceSwitch Job Board is a great resource of freelance gigs and opportunities. New opportunities are posted every day for web developers, and come from a wide range of potential clients. Today we’re showcasing a few of the latest positions that might be perfect for Nettuts+ readers!

    Developer for Online Journal Platform

    Budget: $10,000 + — Location: Anywhere, Australia Preferred

    Calling all talented developers! We are in need of a confident website developer(s) who have experience in NLM XML to PDF/HTML conversion to build an online journals platform which can be managed by the client.

    The website, along with any potential sub-sites, are to be efficiently managed by a single CMS. For a quick overview, the platform needs to be developed with the below features in mind:

    • NLM XML content will be uploaded via the CMS and converted to PDF and HTML.
    • Linking from citing articles, Google Scholar and CrossRef
    • A Reader needs to be integrated for the journals.
    • Usage for subscribers and also pay-per-view
    • Usage report for stats

    Applicants will be required to sign a NDA before receiving additional information about the platform. Successful applicants will be notified before December 20th as to whether they have received the job.

    Find Out More

    Application Developer & HTML5 Specialist

    Budget: $1,000 to $2,500 — Location: Anywhere

    Since we are starting to get a lot of requests from our clients to develop mobile and desktop applications, I really need someone with whom I can create long term trustworthy relationship.

    You need to know your way with Flex and AS3 if possible (I know it is dying but still…) and any other iOS programming you are good at. Please send your skill set and links to completed projects. And of course your hourly fee – please have in mind I need a sub-contractor which means it will not be one time deal.

    We are also looking for HTML5 specialist — please send examples of work in that area as well. I look forward for your responses.

    Find Out More

    Startup Looking for Rails Enthusiasts

    Budget: $500 to $1,000 — Location: Anywhere

    Exvo is a young informal startup running several projects. We’re working on an innovative distributed web based operating system, a distributed platform to manage and run your company from and several other side projects.

    To support these very ambitious plans, we need several additional experienced Rails developers. You can work from anywhere, just as long as you love what you do and enjoy making beautiful code. You will join a team made up of people around the world, who will challenge you to be the best you can be and most of all, have a lot of fun in the process. We currently have three teams of varying sizes.

    We’re looking for junior, intermediate and senior developers with a willingness to learn, good communication skills, a passion for Ruby, a love for Rails, and generally good development skills.

    Find Out More

    Freelance Developer for Web-Chat App

    Budget: $1,000 to $2,500 — Location: United States

    Ever heard of Omegle or Iddin.com? Well I currently have a site that uses a similar model with a much more useful cause that is in need of a complete revamp. I need someone who can re-create a very simple chat script with newly added features. It also needs to be optimized for volume. I also need some membership features, but nothing too extensive.

    Programmer should be proficient with PHP, and Java, Flash is a plus, but must have experience developing a chat app. Features needed include an admin panel, login/registration, user profile with feedback, rating, comments, and a few others. I have a fully written design document ready upon request.

    Find Out More

    And Lots More…

    These are just a handful of the positions currently being offered over at at Job Board, so be sure to head over and take a look at the full selection. We also have a few RSS feeds that will keep you updated with new openings, and you can even choose only to hear about those specific to web development!

    To apply for any of these jobs, simply pick up a FreelanceSwitch membership for an affordable $7 a month. See something you like? Join now!


  • Permalink for '50 Practical, Problem Solving Items'

    50 Practical, Problem Solving Items

    Posted: November 25th, 2011, 11:14am MST by Siddharth

    In the real world, we have to adhere to tight deadlines — so tight that it’s often not feasible to create everything from scratch. In these situations, a well-built and tested template can be of enormous help. I’ll show you some of my favorites today, including everything from landing pages, to resumes, to under construction templates!

    Admin Templates Adminica | The Professional Admin Template Tutorial Image

    Adminica is a cleanly coded, beautifully styled, easily customisable, cross-browser compatible Admin Template and Web Application Interface.

    TERMINATOR – 13 different Admin Backend pages Tutorial Image

    Admin backend template that has a hell of a lot of features. It’s designed with cool “Storm Black / Aluminium” colors to make your backend even better than it is

    White Label – a full featured Admin Skin Tutorial Image

    A full featured skinable and responsive CMS /Admin Panel with custom plugins, widgets, forms, validations, charts, galleries and much more

    Grape – Professional & Flexible Admin Template Tutorial Image

    Grape is a professional and very flexible admin template for huge and small backend solutions. It includes custom plugins, forms, validations, charts, tables, notifications and much more.

    Chameleon Circuit – Full Featured Admin Theme Tutorial Image

    Chameleon Circuit is a beautifully coded full featured admin panel theme ready to be implemented in the back end of your application, or as an intranet theme! The theme, like its namesake, can change colors into anything you want, so instead of a specific number of skins, you have an unlimited variation!

    Admin Control Panel v2 Tutorial Image

    Features a very slick design, rich typography ans is tablet ready (iPad + Android)

    Streamlined – Content Management/CRM Template Tutorial Image

    Streamlined is an admin template for Contact Management and CRM applications. It includes element styles for buttons, tabs, tooltips, progress bar, and others.

    vPanel – Application Framework Tutorial Image

    vPanel is an application framework with all the necessary features and tools you would need to build an admin panel or a software-as-a-service app. It comes with an html template version, so you can use it with other frameworks, and a zend framework ready version.

    Constellation Complete Admin Skin Tutorial Image

    Constellation is a powerfull admin skin for building advanced backends, both for desktop and mobile users. It provides a wide range of styles from data visualization to lists and calendars, all fluid and nestable. This skin is build on HTML5 and CSS3 , and is powered by jQuery for maximum user experience.

    Email Templates FeastMail 2 – Christmas Email Template Tutorial Image

    Feast Mail 2 is a Christmas email template with twelve exclusively designed Christmas collages. It is a great possibility to make warm relations with your clients by sending them this beautiful Christmas greetings email! This email has all you need to promote your products this Christmas and make awesome discount propositions.

    Market – Newsletter and Template Builder Tutorial Image

    Market features 8 Prebuild Layouts, 24 Color Variations, 26 different Elements and 768 HTML Files.

    High Definition E-mail Template Tutorial Image

    Aren’t you making any money from your Apps? Do you think more people should see your awesome designed software? Boost up your views with this extremely clean designed E-mail Template.

    Christmas Season Email Template
    Tutorial Image

    Christmas Season Email Template is a premium HTML email template designed and built especially for the Holiday Season to showcase anything from your mobile or desktop application, portfolio, product(s), services or simply to share news with customers, friends and clients.

    Versatile Newsletter 3 – automated layout creator! Tutorial Image

    The combination between the 11 unique newsletter templates, an easy to use automated layout creator that allows the creation of new newsletter templates instantly, modular layouts that simplify extending/ adapting newsletter templates and robust, properly tested and commented source code makes Versatile Newsletter 3 one of the most complete newsletter packages you can buy at themeforest.

    COPRO – 14 E-mail Templates Tutorial Image

    14 modern corporate newsletter templates made in 7 different color schemes (orange, red, purple, blue, turquoise, green, gray) with inline CSS and flexible table structure for quick and easy layout manipulation (delete/copy/replace table rows inside and between layouts).

    Express Mail Newsletter Template Tutorial Image

    Express Mail is a template design that caters for all businesses. The template comes with all the essential generic information and elements to get you started.

    Virtual Business Cards Stylish Vcard – 11 Modern Skins Tutorial Image Squares – HTML5 vCard/Portfolio Template Tutorial Image

    Squares is a vCard/Portfolio template built with the latest web standards and best practices. Introduce yourself and your work to future clients and employers through a clean and simple web page.

    vCard – a personal profile template vCard – a personal profile template Tutorial Image

    vCard is a simple template designed to showcase your online persona in a list of your social network profiles. There’s also space fo an about page and a fully functional AJAX contact form is included.

    vCard – a personal profile template Tutorial Image

    DotMe is a premium HTML /CSS business card template perfect for any creatives – designers, developers or even photographers.

    Strokes! Personal Website Template Tutorial Image

    Strokes! is a vibrant personal website template, which can be used as a virtual business card on the web.

    Grey & Black – Stylish Online vCard Html Template Tutorial Image

    Grey & Black is a professional online vCard template that is minimal and clean in design. It will help you to create your very own virtual business card, with the ability to showcase your featured projects in style.

    Introducto – Personal Website / V Card Template Tutorial Image

    Introducto is a virtual business card (vcard) template intended for people who want to set up a professional looking web presence in minutes.

    My VCard – Premium Template Tutorial Image

    This is a clean and professional flash like template, perfect for personal website. It’s a simple and minimal looking site with a rare shuffle effect.

    Elegant Vcard Tutorial Image

    Features 6 backgrounds, 4 Pages, fully labeled layered, grid based, easily sliceable PSD files and valid CSS /XHTML

    Under Construction Templates Landerous – Under Construction Page Tutorial Image

    Landerous is just another Under Construction/Coming Soon/Landing template – specially created to tell your visitor that your site is in progress. Clean and professional look with unique design will satisfy all your needs.

    Under Construction page with twitter & pie graph! Tutorial Image

    Make sure your visitors know whats going on with this Under construction site template that features a feed of your latest tweets (which can be easily removed if you dont use twitter) and a pie chart that is easy to change to reflect your progress!

    NEOTERIC—The Ultimate Under Construction Page! Tutorial Image

    NEOTERIC is a clean single page “Under Construction/Coming Soon” template in 10 SKINS designed to keep your users up to date on your site’s progress.

    Easy Coming Soon with Pie Chart, 10 colors + Bonus Tutorial Image

    Easy Coming Soon is an easy and flexible under construction page that will easily let you define your upcoming website and represent it’s current status, supported by a nice looking easily editable pie chart, and ajaxed mailing-list form to keep your visitors up to date.

    Chronos Under Construction Template + WP Theme Tutorial Image

    Easily customize all settings in PHP configuration file or simply install Chronos as a WordPress theme and manage everything from one single page, with a click of a mouse.

    Launch Pad – Full Screen Image Under Construction Tutorial Image

    Launch Pad is a stylish full screen background under construction template with animated progress bar and countdown timer, perfect for showing off your visual work while your website is being developed. Background switcher controls allow you to cycle through background images, which are preloaded to cut loading time. A Fancybox gallery is included so you can show your work.

    Marketing and Landing Pages Promo – Landing Page for Digital Product Sales Tutorial Image

    Sporting a clean minimal style, with lots of breathing space, ensuring nothing get in the way of your product’s showcase. Easy to set up, maintain and easy to replicate for new products, this sophisticated little template is a steal.

    TheLanding Landing Page Tutorial Image

    TheLanding is a simple landing page with half or full header video options! Easily customize the landing page with the included instructions.

    Oceanic Landing Page Tutorial Image

    Oceanic Landing Page is a premium landing page design for any kind of app or download product – even just a service – your choice! With multiple sections available, plus a tabbed area for a huge amount of information if required, this template takes good use of the Z Reading pattern to guide the eye around the design and ultimately convert your visitors in to buyers.

    Unveiled – Ultimate Product Focused Landing Page Tutorial Image

    Unveiled is the ultimate product-centered landing page. With an eye-catching design, the call-to-action high-up the page and an impactful splash intro – this theme is sure to convert your visitors into customers.

    BookPage – Sell your books with Style! Tutorial Image

    BookPage is the landing page template for all those internet marketeers who are releasing their own (E) Book. It has everything you need to show of your hard work.

    Autopilot Landing Page (3 Themes) Tutorial Image

    Autopilot is a landing page design best suited for all businesses and industries. The template comes with one HTML and one PHP file (contact form). It comes with three themes – realistic, festive and generic.

    Resumes and CVs Clean CV / Resume Html Template + 4 Bonuses! Tutorial Image

    Clean Cv / Resume is a html template that will help you set up a professional online CV in minutes and broaden the chance of finding a suitable job as many recruiters resort more and more to browsing online for prospective applicants instead of advertising their position and calling for applicants.

    Awesome Online Resume/CV Tutorial Image

    This is a clean, modern and colorful (optional) Resume/CV theme suited for everyone! It is very easy to edit and includes 10 minutes of video documentation showing you exactly what to do!

    Bold – CV / Resume Template – Minimal & Smart Tutorial Image

    Bold is a minimal and clean one-page CV / resume HTML + PHP template featuring print-ready and mobile-ready versions, downloadable PDF version generated on-the-fly, working Ajax contact form, jQuery lightbox gallery and social media section. It is also very easily editable and configurable.

    Professional & Clean HTML CV RESUME Tutorial Image

    This template is a complete HTML CV Resume. Useful to present your skills and your personal portfolio.

    Pinstripe – Premium Resume / CV Template Tutorial Image

    This is a professional pinstriped CV / Resume with a plethora of slick jQuery effects. A great way to present yourself to any potential employers / clients.

    Typographic CV – impressive resume template Tutorial Image

    Typographic CV is online resume / CV template. It was created to impress your future employers or clients. And it definitely will: strong typographic design, good visual hierarchy, unique layout, cool gallery section and much more.

    JumpBox – Animated Resume/Portfolio Tutorial Image

    Jump Box is a premium Ajax based CV(Resume)/Portfolio animated website template. This template is perfect to use for small websites. It can be used as a CV/Portfolio Template, Landing Page, or any website with a little number of pages.

    404 and Error Pages Lost in Space – Error 404 Lost in Space – Error 404

    Tutorial Image

    Simple and aesthetically pleasing template with animated background. Valid HTML and CSS. Ready for all common HTTP errors, like 401, 403, 404, 500 and 503 or for many other purposes.

    Modern Custom 404 Error Page Tutorial Image

    You can use this Modern Custom 404 Error Page pack for any type of errors on your site. It is designed with usability in mind – to help the user get what he wants . It’s fully customizable and browser compatible and you can choose between 16 color schemes.

    Save me – 404 Error Page Tutorial Image

    “Save me” is an unique new error page, that focuses on helping the user through the frustration of getting a website error, in an user friendly and intuitive way.

    Cosmo Error Page Tutorial Image

    Cosmo Error page. It has all you need – links to your other pages, links to your social profiles, working contact form.

    Custom 404 Error Page – Missing Jigsaw Piece Tutorial Image

    Missing jigsaw piece custom 404 error page, in two styles; grey and dark gloss. The layout has subtle embossed text effects and textures, giving you an original look to the design.

    Lost in the Clouds – Error 404 Tutorial Image

    Valid HTML and CSS. Ready for all common HTTP errors, like 401, 403, 404, 500 and 503 or for many other purposes.


  • Permalink for 'Easy Package Management for CodeIgniter with Sparks'

    Easy Package Management for CodeIgniter with Sparks

    Posted: November 24th, 2011, 9:31am MST by RJ Zaworski

    Sparks is a new package-management system for CodeIgniter that extends the core with support for gem-like sparks.

    This tutorial interweaves an entry-level overview of the architecture and usage of the sparks system with the creation of dovecote—a simple spark for managing RSS data.

    Introduction

    Packages are blocks of recyclable code that can make developers’ lives a whole lot easier.

    CodeIgniter’s developers have long salivated over package managers like gems and npm, systems that empower their respective communities with tools and a central repository for developing, recycling, and sharing useful application components with each other. Now, the wait is over. Thanks to a new system—sparks—CodeIgniter developers can finally rejoice, as a growing package management system is finally their own.

    Overview

    If you haven’t worked with them before, just think of packages as blocks of recyclable code that can make developers’ lives a whole lot easier. Maybe you need an interface to an storage bucket in Amazon’s cloud? Skip the late nights pouring over S3 documentation and just grab the spark.

    For its part, the sparks system consists of three parts:

    1. A central repository (getsparks.org) for storing and sharing sparks
    2. A utility for managing the sparks installed in a given CodeIgniter app
    3. The sparks themselves

    For the purposes of this tutorial, we’ll introduce the first two but focus on spark development and some basic considerations in developing a spark. Sound good? Let’s see how it’s done.

    Step 1: Installing Sparks

    It’s official: sparks is slated for integration into CodeIgniter’s core, possibly as soon as the upcoming 2.1 release. But since it isn’t part of a default installation—yet—you’ll need to set the system up manually.

    If you’re on OSX or Linux, or if you have PHP’s command-line interface installed on Windows, installation is as simple as installing a clean copy of CodeIgniter and issuing the following in the installation directory:

    $ php -r "$(curl -fsSL [getsparks.org] 

    If all went well, you should see something like this:

    Installing the sparks system

    If for some reason that didn’t work, or if you’re on Windows and haven’t added PHP to your command path, you can also install sparks manually. It’s a little more work, but the result is the same:

    1. Adding a directory named sparks in the root of your codeigniter directory
    2. Adding a custom Loader Class to application/core/MY_Loader.php
    3. (optional) Downloading and extracting the sparks command line utility into your codeigniter directory

    Your CodeIgniter installation should now be patched to support sparks.

    Step 2: Getting Started

    In medieval Europe, every manor house included a small outbuilding for pigeons to nest called a dovecote. Since we’ll be building a spark that involves both tweeting and feed, the name is appropriate enough. But it also meets the only requirement on naming: to be included in the repository at GetSparks.org,

    GetSparks project names must be unique

    Outlining the Spark

    Before we can code, we’ll need to layout a project. In the sparks directory in the root of your CodeIgniter installation (create it, if it doesn’t exist), add a new folder to hold the spark:

    /sparks/dovecote

    Convention dictates that sparks are organized by version, so we’ll need a subfolder to hold the first draft. 0.0.1 is a good place to start.

    /sparks/dovecote/0.0.1

    This folder is where all the action will take place. When the rest of the tutorial refers to our “spark directory”, this is it.

    The spark.info File

    Things are looking pretty bare so far, but we’re ready to start filling them out. The first piece in the spark–and the only file technically required by the spark utility—is spark.info. Create a new file called spark.info in your spark directory, and add the following:

    name: dovecote
    version: 0.0.1
    compatibility: 2.0.2
    dependencies:
       Atomizer: 0.0.1
    tags: ["twitter","api","social"]
    

    These fields represent all the information the spark utility needs manage the version and dependencies of all the sparks in this CodeIgniter installation. The utility will look for five things, but only the first three are required:

    • name — the unique spark id
    • version — current version
    • compatibility — minimum CodeIgniter version
    • dependencies — (optional) other sparks required by this spark
    • tags — (optional) tags that describe this spark

    Even if you aren’t planning to use the spark utility yourself, it’s still polite to include a spark.info file with any spark you plan on distributing. One of the real advantages to managing sparks this way, rather than pasting them directly into the sparks directory, is that the spark manager can use the compatibility, dependency, and version information in each spark to ensure nice play with the current CodeIgniter installation—and each other. There’s another benefit, too, as we will see in a moment: sparks installed outside of the manager utility must have their dependencies installed manually.

    Organizing the Spark

    With the info file written, it’s time to give the spark some structure. Create four new folders in the spark directory:

    • config
    • helpers
    • libraries
    • views

    If you’ve worked with CodeIgniter before, these are probably familiar names. CodeIgniter’s loader class treats sparks as packages, meaning that the contents of these directories are checked for any application components that can’t be found in the /application directory. For now, this applies to five types of resources:

    • configs
    • helpers
    • libraries
    • models
    • views
    Step 3: Writing the Spark

    Before we begin coding, take a moment to ensure that your spark directory contains all the necessary pieces.

    Installing the sparks system

    Everything in order? Let’s proceed.

    Create a file in the newly-created config directory and name it dovecote.php. We’ll store a few basic options here to tell the spark where it can find RSS data:

    <?php /** config/dovecote.php **/
    
    // Username to retrieve tweets from:
    $config[ 'twitter' ]    = 'getsparks';
    
    // API endpoint to query for tweets:
    $config[ 'twitterURL' ] = 'http://twitter.com/statuses/user_timeline/%s.rss';
    
    // Feed carrying RSS data:
    $config[ 'feedURL' ]    = 'http://feeds.bbci.co.uk/news/rss.xml';
    
    ?>
    

    Not much to it—we’ve defined a twitter username (@getsparks) to grab tweets from, provided an API endpoint for Twitter’s Timeline API, and added an additional URL to search for RSS stories.

    Now the spark knows where data can be found, it’s time to go retrieve some feeds. To do this, we’ll need to create a library—call it dovecote.php—and save it in the libraries directory:

    <?php /** libraries/dovecote.php **/ 
    
    class dovecote {
    
        protected $ci, $timeline;
    
        public function __construct() {
            $this->ci = &amp;get_instance();
        }
    
        public function retrieve() {
    
            // build twitter request URL
            $twitterURL = sprintf( $this->option( 'twitterURL' ), $this->option( 'twitter' ) );
    
            // get RSS Data
            $tweets = $this->ci->atomizer->loadURL( $twitterURL );
            $feed = $this->ci->atomizer->loadURL( $this->option( 'feedURL' ) );
    
            // set channel information for new feed
            $info = array(
                'title' => 'Convolved feed'
            );
    
            // mix the two feeds together
            $this->timeline = $feed->convolve( $tweets, $info );
    
            return $this->timeline;
        }
    
        public function publish() {
            header('content-type: application/rss+xml');
            echo $this->timeline->save();
        }
    
        // retrieve an option ($key) from config files
        protected function option( $key ) {
            return $this->ci->config->item( $key );
        }
    }
    
    ?>
    

    This library provides helper functions to retrieve options from our config file and publish an RSS feed, but the critical piece is retrieve(). This function grabs RSS data from the providers described in dovecote’s configuration file in several steps:

    • First, the address of the Twitter RSS feed is generated. Config outlined a username (twitter) and an endpoint (twitterURL); now, the two are combined using sprintf.
    • Next, the RSS data in each feed are retrieved using the loadURL function the atomizer library. This function returns an “AtomizerFeed” object that provides some useful functions for manipulating RSS data.
    • Finally, AtomizerFeed’s convolve operation is used to combine the two feeds’ items into a single feed, which is returned.
    • At this point, we’re almost ready to fire up dovecote in a live application. We just need to check to make sure that our application includes all of dovecote’s dependencies and that the spark itself will load correctly.

      Step 4: Dependencies

      When we wrote spark.info, recall the line where we described dovecote’s dependencies:

      Dependencies:
         Atomizer: 0.0.1
      

      This means that dovecote relies on another spark—Atomizer—to function. Once sparks are committed to the getsparks.org repository, the manager utility will download dependencies automatically. While we remain in local development, however, we’ll need to do this ourselves.

      If you’re using the sparks manager, you can install Atomizer by navigating to your CodeIgniter directory and invoking the manager’s install function:

      php tools/spark install -v0.0.2 atomizer
      

      Note: If you’re on Windows, you will need to invoke php tools\spark install -v0.0.2 atomizer instead.

      If you aren’t using the manager, or if the installation didn’t complete successfully, you can download Atomizer from Github and extract it into your application’s sparks directory next to the folder containing dovecote.

      Step 5: Autoloading

      Before dovecote will be available to other parts of the application, we’ll need to make sure that it will load correctly. Return to the config folder in your spark directory and paste the following into a new file called autoload.php.

      <?php /** config/autoload.php **/
      
      // load default configuration
      $autoload['config'] = array( 'dovecote' );
      
      // load dependency
      $autoload['sparks'] = array( 'atomizer/0.0.2' );
      
      // load library
      $autoload['libraries'] = array( 'dovecote' );
      ?>
      

      Whenever CodeIgniter loads a spark, it will attempt to load all the resources listed in autoload.php as well. This allows sparks authors to define the resources that users should have immediate access to whenever they load the spark. Because the dovecote library is specified here, for instance, we will have immediate access to the retrieve function as soon as the spark is loaded.

      It’s worth mentioning that the resources described in autoload.php need not reside in the spark directory. As long as they’re located somewhere in CodeIgniter’s search path, the application should be able to find them. Notice atomizer is being loaded in the example above; it wouldn’t do much good to list a spark’s dependencies but be unable to load them!

      Save the autoload file, and let’s load it all up. In the welcome controller in your main application (/application/controllers/welcome.php), add the following:

      public function dovecote() {
          $this->load->spark( 'dovecote/0.0.1' );
          $this->dovecote->retrieve();
          $this->dovecote->publish();
      }

      Let’s walk through that:

      1. We ask CodeIgniter to load dovecote, knowing that all the resources requested in config/autoload.php will be loaded as well
      2. dovecote’s retrieve function is used to get copies of the RSS feeds described in config/dovecote.php
      3. The combined timeline produced by retrieve is served up as an RSS feed using dovecote’s publish function
      See it in Action

      Browse to welcome/dovecote in your browser, and you should be greeted with an RSS feed chronicling the tweets and articles that dovecote has collected.

      Step 6: Building on the Spark

      Let’s make dovecote a little more useful. First, we’ll create a basic view template to show the title of each article in our timeline:

      <?php /** views/dovecote_timeline.php */ ?>
      
      <h3>Recent Happenings:</h3>
      <ol>
      <?php foreach ($items as $item): ?>
          <li><?php echo $item->title; ?></li>
      <?php endforeach; ?>
      </ol>
      

      Next, we’ll make the view accessible by providing a helper function that other parts of the application can use to render the timeline in HTML.

      <?php /** helpers/dovecote_helper.php */
      
      function dovecote_timeline() {
      
          $ci = &amp;get_instance();
      
          $feed = $ci->dovecote->retrieve();
      
          $data = array(
              'items' => $feed->items()
          );
      
          $ci->load->view( 'dovecote_timeline', $data );
      }
      
      ?>
      

      The dovecote_timeline function and its eponymous view can now be used to render the timeline anywhere in our application. But in keeping with CodeIgniter’s only-what-you-need philosophy, we won’t make it automatically available via autoload.php. Instead, we’ll need to load the helper manually whenever it is needed. Return to your application’s welcome controller, and update the dovecote function to generate an HTML version of the feed:

      public function dovecote() {
          $this->load->spark( 'dovecote/0.0.1' );
          $this->load->helper( 'dovecote' );
      
          $this->dovecote->retrieve();
      
          // call the helper function
          echo dovecote_timeline();
      }
      

      Refresh your browser, and you should now see a list of all the items in dovecote’s timeline.

      An HTML version of the dovecote timeline Wrapping Up

      Congratulations! You’re now the owner of a very simple spark, but there’s plenty more that can be done. Before sending dovecote out for action, you may consider writing additional functions. The details are up to you, but some useful features might include:

      • caching of API responses
      • views for beautifying the data retrieved
      • data persistence to save older timeline items (check the feed license, first!)

      This tutorial offers the barest outlines of what can be done with sparks and introduces the advantages that sparks can provide in minimizing repetition and speeding up development.

      Working on a spark of your own? Having issues getting started out? Share a little more in the comments below and thank you so much for reading!


  • Permalink for 'Getting Started with MongoDB'

    Getting Started with MongoDB

    Posted: November 23rd, 2011, 2:29pm MST by Matthew Setter

    Ready to get in and start learning about MongoDB, one of the coolest technologies for web developers?

    In this new series, you’ll go from beginner to pro and be able to use Mongo just as easily as MySQL in your web apps. But first, let’s look at the basics.

    Why MongoDB?

    What if you could store the programmatic models almost exactly like you model them?

    In object-oriented development, we’re encouraged to approach code development through logical models, so that we can more readily conceptualise it in our mind. When we do this, we’re better able discern the logical operations used to interact with it and information that it would contain at different times.

    What if you could store the programmatic models almost exactly like you model them? What if you could store them as they are instead of in a series of rows in tables? By learning about MongoDB, you’re going to be able to do just that!

    In this series, we’ll be learning everything from the basics of MongoDb, such as creating, updating and deleting databases and records, to being able to perform complex searches for data and elementary data mining with MapReduce. So, without much ado – let’s get started!

    Note: This tutorial is done from the perspective of NIX based system a la Mac OSX, Linux BSD and so on. But you should be able to follow along if you’re running Windows pretty well as there are builds for most platforms.

    Step 1 : Installing Mongo

    Ok, so here’s where the fun begins. We’re going to get started by installing Mongo. Go to the MongoDb website and click on the downloads link.

    The MongoDb link to downloads

    This will bring you to a page where you can grab a build for your platform and architecture.

    The MongoDb download options

    This tutorial only covers stable releases, so please do not grab a nightly build. Once it’s downloaded, please install it as per the requirements of your platform.

    If you’re on a Nix machine, then please use its package manager to install the latest version for your platform.

    With that out of the way, fire up a terminal and type in mongo. That will open up the Mongo shell and let us get under way. All being well, you’ll see output similar to below:

    The MongoDb shell

    If you see that, then you’re ready to go.

    Step 2 : Creating a Database/Inserting Records

    Initially, no database is created. But don’t worry, they’ll instantly be created when we start inserting our records, which we’re going to do right now. Copy the content below and paste it in your mongo shell

    db.nettuts.insert({
        first: 'matthew',
        last: 'setter',
        dob: '21/04/1978',
        gender: 'm',
        hair_colour: 'brown',
        occupation: 'developer',
        nationality: 'australian'
    });
            db.nettuts.insert({
        first: 'james',
        last: 'caan',
        dob: '26/03/1940',
        gender: 'm',
        hair_colour: 'brown',
        occupation: 'actor',
        nationality: 'american'
    });
    db.nettuts.insert({
        first: 'arnold',
        last: 'schwarzenegger',
        dob: '03/06/1925',
        gender: 'm',
        hair_colour: 'brown',
        occupation: 'actor',
        nationality: 'american'
    });
    db.nettuts.insert({
        first: 'tony',
        last: 'curtis',
        dob: '21/04/1978',
        gender: 'm',
        hair_colour: 'brown',
        occupation: 'developer',
        nationality: 'american'
    });
    db.nettuts.insert({
        first: 'jamie lee',
        last: 'curtis',
        dob: '22/11/1958',
        gender: 'f',
        hair_colour: 'brown',
        occupation: 'actor',
        nationality: 'american'
    });
    db.nettuts.insert({
        first: 'michael',
        last: 'caine',
        dob: '14/03/1933',
        gender: 'm',
        hair_colour: 'brown',
        occupation: 'actor',
        nationality: 'english'
    });
    db.nettuts.insert({
        first: 'judi',
        last: 'dench',
        dob: '09/12/1934',
        gender: 'f',
        hair_colour: 'white',
        occupation: 'actress',
        nationality: 'english'
    });
    

    All good? Excellent! To confirm that the database and accompanying records have been created, type in the following command:

    db.nettuts.find()

    If everything went to plan, then you will see the following output:

    Finding all records

    This shows that all of the records were created in the database. One thing to note before we go any further is the id field. This is auto generated by Mongo for you, if you don’t specify an id. The reason is that every record must have a unique id field.

    You can see that we have one record for each of the ones that we insert – now we’re ready to start querying them.

    Step 3 : Searching For Records

    You remember the previous command? It retrieved and displayed every record in the database. Helpful, yes, but how do you be more specific? How do you find all female actors, filtering out the males? That’s a good question and the answer is selectors.

    Selectors

    Selectors are to Mongo what where clauses are to SQL. As with where clauses, Mongo selectors allow us to do the following:

    • specify criteria that MUST match. i.e., an AND clause
    • specify criteria that CAN optionally match. i.e., an OR clause
    • specify criteria that MUST exist
    • and much more…
    Records That MUST Match

    Let’s start with a basic selector. Say that we want to find all actors that are female
    . To accomplish that, you’ll need to run the following command:

    db.nettuts.find({gender: 'f'});

    Here we have specified that gender must be equal ‘f’.

    Running that command will return the following output:

    Finding all female records

    What if we wanted to search for male actors? Run the following command:

    db.nettuts.find({gender: 'm'});

    We’ll get the following results:

    Finding all male records Searching with Multiple Criteria

    Let’s step it up a notch. We’ll look for male actors that are English.

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}]});

    Running that will return the following results:

    Finding all male, English, records

    What about male actors who are English or American. Easy! Let’s adjust our earlier command to include the Americans:

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}); 

    For that query, we’ll see the following results:

    Finding all male, English or American, records Step 4 : Sorting Records

    What if we want to sort records, say by first name or nationality? Similar to SQL, Mongo provides the sort command. The command, like the find command takes a list of options to determine the sort order.

    Unlike SQL, however we specify ascending and descending differently. We do that as follows:

    • Ascending: -1
    • Descending: 1

    Let’s have a look at an example:

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1}); 

    This example retrieves all male, English or American, actors and sorts them in descending order of nationality.

    Finding all male, English or American, records sorted by nationality

    What about sorting by nationality in descending order and name in ascending order? No problem at all! Take a look at the query below, which is a modified version of the last one we ran.

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1, first: 1}); 

    This time we retrieve the following results et:

    Finding all male, English or American, records sorted by nationality first and first name second

    You can see that this time Arnold Schwarzenegger is placed before Tony Curtis.

    Step 5 : Limiting Records

    What if we had a pretty big data set (lucky us, we don’t) and we wanted to limit the results to just 2? Mongo provides the limit command, similar to MySQL and allows us to do just that. Let’s update our previous query and return just 2 records. Have a look at the following command:

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).limit(2); 

    From that command, we’ll get the following results:

    Limit output to 2 records

    If we wanted the third and fourth records, i.e., skip over the first two? Once again, Mongo has a function for that. Have a look at the further customisation of the previous command:

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).limit(2).skip(2); 

    Running that will return the following results:

    Limit output to the 3rd and 4th records

    You can see from the original result set that the first two were skipped.

    Step 6 : Updating Records

    As expected, Mongo provides an option to update records as well. As with the find method and SQL queries, you need to specify the criteria for the record that you want to modify, then the data in that record that’s going to be modified.

    Let’s say that we need to update the record for James Caan specifying that his hair is grey, not brown. Well for that we run the update function. Have a look at the example below:

    db.nettuts.update({first: 'james', last: 'caan'}, {$set: {hair_colour: 'brown'}});

    Now when you run that, if all went well, there won’t be anything to indicate whether it was a success or failure. To find out if the record was update properly, we need to search for it. So let’s do that.

    db.nettuts.find({first: 'james', last: 'caan'});

    After this you will see the following result:

    Update record

    This shows that the update worked. One word of caution though, if you don’t pass in the $set modifier, then you will replace the record, if it’s available, instead of updating it. Be careful!

    Step 7 : Deleting Records

    I think by this stage, you have really started to get the idea of working with Mongo. That’s right, if you want to delete a record, you have to pass in a set of selectors, as you also would with SQL, to determine the set of records to delete. If you don’t do this, you will delete all records – and the database.

    So, let’s say that we don’t want James Caan in our list of actors. Let’s remove him from the database using the following command:

    db.nettuts.remove({first: 'james', last: 'caan'});

    As with update, no visible output is provided to indicate whether we were successful or not – so let’s do a search to double check.

    db.nettuts.find({first: 'james', last: 'caan'});

    After this, you should see no results returned. If that’s what you’ve found, then we’ve successfully deleted James Caan from our database. But what if we want to delete all the records from the database?

    Well, to do that, just remove the selectors from the previous call to remove, as below.

    db.nettuts.remove();
     db.nettuts.find();

    After running both commands above, we’ll see no output, indicating that the database, with all records have now been removed.

    Remove all records Conclusion

    In this rapid introduction to using MongoDB we looked at:

    • What Mongo is
    • How to install it
    • How to create, find, update and delete records

    With this knowledge, you can go, practice, and learn more about this wonderful technology. If you want more information, feel free to check out the MongoDb website or follow @mongodb on Twitter.

    In the next tutorial, we’re going to start to learn more about complex queries. So stay tuned and thank you so much for reading.


  • Permalink for 'How to Generate a Complete Excel Spreadsheet From MySQL'

    How to Generate a Complete Excel Spreadsheet From MySQL

    Posted: November 22nd, 2011, 11:15am MST by David Brumbaugh

    A CSV (Comma Separated Value) file is usually sufficient for exporting MySQL data as an Excel Spreadsheet. These CSV files are data only though. A real Excel spreadsheet has formatting, formulas and perhaps even graphics — the difference between a simple method of data transfer and a professional report.

    This tutorial shows how to use open source PHP components to create "real" Excel spreadsheets from MySQL SELECT statements. Interested? Let’s get started!

    Overview

    PHPExcel is a set of PHP classes that allow you to to read and write different spreadsheet file formats as well as manipulate the spreadsheets themselves. Before you begin, you’ll need a copy of PHPExcel. To get the latest copy of the PHPExcel component, go to [www.phpexcel.net] and download the latest stable release.

    An Excel spreadsheet is a series of pages (called Worksheets) which have numbered rows and alphabetically labeled columns.

    The Fundamental Relationship Between Data Tables and Spreadsheets

    A SQL SELECT statement returns a result set that is a collection of labeled columns with the data contained in rows. In PHP/MySQL, each row of a result set can be (and often is) represented by an associative array, where the key to the associative array is the column name.

    An Excel spreadsheet is a series of pages (called Worksheets) which have numbered rows and alphabetically labeled columns.

    The general technique will be to map one SQL statement to one spreadsheet page (worksheet), specifically by matching column names in the associative array returned by the PDO fetch command to alphabetical column labels on the spreadsheet.

    Step 1: Understand How to Properly Label Alphabetical Columns

    The key to this technique is the underlying column labeling algorithm, which will allow you to properly label alphabetical columns for an arbitrarily large number of columns. As previously noted, in an Excel spreadsheet, columns are identified with letters and rows are identified with numbers. If your query will contain less than 26 columns, you could simply stop at "Column Z". However, many queries have substantially more columns than that.

    Excel Column Labelling Scheme

    When the column labels get to Z a second letter is added: "A… Z,AA, AB … AZ". After "AZ" comes "BA" as shown below.

    The Column Labeling Algorithm

    The following PHP snippet shows how to label column headers from "A" to "ZZ".

    $keys = array_keys($row); // Get the Column Names
    $min = ord(&quot;A&quot;); // ord returns the ASCII value of the first character of string.
    $max = $min + count($keys);
    $firstChar = ""; // Initialize the First Character
    $abc = $min;   // Initialize our alphabetical counter
    for($j = $min; $j <= $max; ++$j)
    {
    	$col = $firstChar.chr($abc);   // This is the Column Label.
      $last_char = substr($col, -1);
    	if ($last_char> "Z") // At the end of the alphabet. Time to Increment the first column letter.
    	{
    		$abc = $min; // Start Over
    		if ($firstChar == "") // Deal with the first time.
    			$firstChar = "A";
    		else
    		{
    			$fchrOrd = ord($firstChar);// Get the value of the first character
    			$fchrOrd++; // Move to the next one.
    			$firstChar = chr($fchrOrd); // Reset the first character.
    		}
    		$col = $firstChar.chr($abc); // This is the column identifier
    	}
    	/*
    		Use the $col here.
       */
    
      $abc++; // Move on to the next letter
    }
    

    This algorithm will not go beyond ZZ. The algorithm is implemented (in a slightly different form) in the accompanying source file in the MySqlExcelBuilder::mapColumns member function.

     

    Step 2: Format and Test Your SQL Statement A Simple Schema

    The schema below shows a simplified customer/order relationship. The SQL CREATE statements for the schema below are included in the file xls_sample.sql in the zip file that accompanies this tutorial.

    A "Quick and Dirty" SELECT Statement

    It’s common practice to simply grab the data quickly from these tables in a SQL statement that looks something like this:

    SELECT * FROM `order`,`customer`,`order_item`
             WHERE `customer_id` = `customer`.`id`
             AND item_id = `order_item`.`id`
    

    The primary advantage of this "quick and dirty" statement is that it’s fast and easy to program. The results usually don’t look very good.

    PHPMyAdmin is a tool for MySQL database administration that comes standard with many hosting plans. To prototype and test your spreadsheet pages you can use the SQL composition tools that come with PHPMyAdmin.

    The following screenshot shows the result of the query above:

    And a close up of some of the columns shows that the column names are meaningful to programmers, but unattractive to business users.

    The column names are not capitalized according to "real world" rules, there are underscores instead of spaces, etc.

    Get More Attractive Results From a SELECT Statement

    We want to format the SELECT statement to look like business a report on the spreadsheet. So, using the PHPMyAdmin tool, edit the SQL statement so that the column names are real words and only the columns the business user wants to see are displayed. The reformatted SQL Statement looks like:

    SELECT `name` AS `Customer Name`,
            `email_address` AS `Email Address`,
            CONCAT( right(`phone_number`,3) , '-' , mid(`phone_number`,4,3) , '-', right(`phone_number`,4)) AS `Phone Number`,
            `item_sku` AS `Part Number`,
            `item_name` AS `Item Name`,
             `price` AS `Price`,
            `order_date` as `Order Date`
     FROM `order`,`customer`,`order_item`
     WHERE `customer_id` = `customer`.`id`
             AND item_id = `order_item`.`id`
    

    Resulting in :

    The prototype above demonstrates very much what the spreadsheet page will look like.

    Step 3: Displaying A MySQL Result Set on A Spreadsheet Page

    The Class MySqlExcelBuilder encapsulates the functionality necessary to add SQL statements to an Excel spreadsheet page using PDO and PHPExcel. The full class is in the accompanying zip file.

    The MySqlExcelBuilder Class

    This class enables an arbitrary number of SQL result sets to be placed on named pages within an Excel spreadsheet. The following code snippet shows the important data members.

    <?
    class MySqlExcelBuilder
    {
            protected $pdo; // PHP Data Object
            public $phpExcel; // PHP Excel
            protected $sql_pages = array(); //Sheet Name, Sql Statement, Options
    
    • The $pdo data member is the PHP Data Object used to query the database.
    • The $phpExcel data member is the PHPExcel object used to build and manipulate the spreadsheet.
    • The $sql_pagesarray holds the SQL Statement and the page formating/naming information.
    • The constructor (not shown) initializes the PDO and PHPExcel data members.
    Preparing Each Page

    The spreadsheet image below is a prototype made in Excel to show what we might want the spreadsheet to look like when it is rendered.

    The add_page member function is used to add SQL Statements to the named pages:

    public function add_page($wsName,$sql,$total_colums=null,$start_col="A",$start_row="1")
    {
    	 // $wsName, is the Work Sheet Name that will be shown on the tab at the bottom of the spreadhseet
    	$this-&gt;sql_pages[$wsName]['Sql'] = $sql; // This is the statement to be executed
    	$this-&gt;sql_pages[$wsName]['Col'] = $start_col; // This is the column to start putting data into.
                                                    // Note that it must be between "A" and "Z", staring in Column "AA" and after is not supported.
    	$this-&gt;sql_pages[$wsName]['Row'] = $start_row; // This the row number to start putting data into
    	$this-&gt;sql_pages[$wsName]['Totals'] = $total_colums; // This is a comma delimted list of Column Names (NOT Column Labels) that will be totaled.
                                                          //If null it will be ignored.
    
    }
    

    The sql_pages data member holds the information we want to use to put sql on pages.

    Member Function Usage Example

    This snippet is an example of how to use the add_page member function:

    $xls_sql = new MySqlExcelBuilder('database','username','password');
    $sql_statement = &lt;&lt;&lt;END_OF_SQL
    
    SELECT `name` AS `Customer Name`,
            `email_address` AS `Email Address`,
            CONCAT( right(`phone_number`,3) , '-' , mid(`phone_number`,4,3) , '-', right(`phone_number`,4)) AS `Phone Number`,
            `item_sku` AS `Part Number`,
            `item_name` AS `Item Name`,
             `price` AS `Price`,
            `order_date` as `Order Date`
     FROM `order`,`customer`,`order_item`
     WHERE `customer_id` = `customer`.`id`
             AND item_id = `order_item`.`id`
             AND `item_sku` = 'GMG1'
    
    END_OF_SQL;
    
    $xls_sql->add_page('Gold Mugs',$sql_statement,'Price');
    

    The illustration below shows how the add_page member function should map to the spreadsheet.

    Step 4: Building the Spreadsheet Understanding PHPExcel

    If you understand how to manipulate an Excel spreadhseet with your mouse and keyboard, you can become quite adept at using PHPExcel. PHPExcel is built on the principle of manipulating the underlying spreadhseet model using commands that are similar to the commands you would give to Excel itself. The PHPExcel Developer Documentation has details.

    The getExcel() Member Function

    The member function getExcel()uses PHPExcel to build each of the worksheets from the SQL statements you defined in Step 3. When the worksheets have been built, it returns the PHPExcel object to the caller. There are four major sections of the getExcel member function described below.

    A. Iterate Through the Pages

    The main loop of this member function iterates through the pages previously added with add_page. In each iteration, it creates the corresponding page in the phpExcel object and then adds the data. The createSheet member function of PHPExcel is used to create a new worksheet for each page previously added.

            public function getExcel()
            {
                $i = 0;
                foreach($this->sql_pages as $wsName=>$page)
                {
                    $start_of_page = true;
                    $sql = $page['Sql'];
                    $start_col = $page['Col'];
                    $start_row = $page['Row'];
                    $this->phpExcel->createSheet();
                    $sheet = $this->phpExcel->setActiveSheetIndex($i);
    
                    if ($sh = $this->pdo->query($sql))
                    {
    

    The illustration below shows how the code corresponds to the spreadsheet. The column_map is discussed in the next section.

    B. “Start of Page” Logic

    Each page has special formatting at the start. The first time a row is retrieved from the database for a particular page, it performs the tasks necessary to perform the start-of-page formating. It invokes the “mapColumns” member function that was discussed in Step 1. PHPExcel, like Excel uses the a LetterNumber pair to identify a particular cell. In MySqlExcelBuilder it’s referred to as a cellKey. A cell key is built by concatenating a column label and a row number.

    	$rowNum = $start_row;
    	while($row = $sh->fetch(PDO::FETCH_ASSOC))
    	{
    		$keys = array_keys($row); // Get the Column Names
    		if ($start_of_page) // Initialize the Page
    		{
    			$this->mapColumns($wsName,$keys,$start_col);
    			foreach($keys as $key)
    			{
    			   $col = $this->column_map[$wsName]['xls'][$key];
    			   $cellKey = $col.$rowNum;
    				$sheet->setCellValue($cellKey,$key);
    				// The next two lines are for formatting your header
    				$style = $sheet->getStyle($cellKey);
    				$style->getFont()->setBold(true);
    				$sheet->getColumnDimension($col)->setAutoSize(true);
    			}
    			$rowNum++; // The next row is for data
    			$start_of_page = false; // Done with Intialization
    		}
    

    Some additional things to note in the above code snippet:
    * setCellValue – Puts the actual value in the field. Note that a cell is a member of a worksheet. The specific cell is identified by the cellKey variable.

    * getStyle – This returns a reference to the style attribute of a particular cell, so it can be manipulated.
    * getColumnDimension is a method of the worksheet object. A column dimension (width) is associated with the col variable.

    C. Fill in the Data

    Thanks to the preparation and column mapping, the process of actually putting each data item in the cell is now relatively trivial. We look up the spreadsheet column for a particular data column, build a cell key and then put the value in a cell.

    foreach($keys as $key) // Put the value of the data into each cell
    {
    	 $col = $this->column_map[$wsName]['xls'][$key]; // Get the appropriate column
    	 $cellKey = $col.$rowNum; // Build the column key
    	 $val = $row[$key]; // Get the data value
    	 $sheet->setCellValue($cellKey,$val); // Put it in the cell.
    }
    $rowNum++;
    
    D. Add in the Formulas

    The last part of getExcel() shows how to add forumulas to a PHPExcel spreadhseet. In this case, it’s a column total. PHPExcel puts formulas into cells exactly as you would with an Excel Spreadsheet. The value of a cell starts with an equal sign ( = ) and contains a forumla. In this case, the SUM of a range of data cells. See below:

    And now the code:

     $col = $this->column_map[$wsName]['xls'][$key];
    	// Add the Total Label
    	$cellLabelKey = $col.$rowNum;
    	$total_label = "Total $key";
    	$sheet->setCellValue($cellLabelKey,$total_label);
    	$style = $sheet->getStyle($cellLabelKey);
    	$style->getFont()->setBold(true);
    
    	// Add the actual totals
    	$total_row = $rowNum+1;
    	$cellKey = $col.$total_row;
    	$startTotal = $col.$start_row;
    	$endTotal = $col.$this->sql_pages[$wsName]['lastDataRow'];
    	$total_forumla = "=SUM($startTotal:$endTotal)";
    	$sheet->setCellValue($cellKey,$total_forumla);
    	$style = $sheet->getStyle($cellKey);
    	$style->getFont()->setBold(true);
    

     

    Step 5: Put on the Finishing Touches

    After you’ve gotten an Excel spreadsheet that’s been filled with data from your MySQL database with getExcel it’s time to put the finishing touches on the spreadsheet. In this example, we add a title to each worksheet.

    // Get the spreadsheet after the SQL statements are built...
    $phpExcel = $mysql_xls->getExcel(); // This needs to come after all the pages have been added.
    
    $phpExcel->setActiveSheetIndex(0); // Set the sheet to the first page.
    // Do some addtional formatting using PHPExcel
    $sheet = $phpExcel->getActiveSheet();
    $date = date('Y-m-d');
    $cellKey = "A1";
    $sheet->setCellValue($cellKey,"Gold Mugs Sold as Of $date");
    $style = $sheet->getStyle($cellKey);
    $style->getFont()->setBold(true);
    
    $phpExcel->setActiveSheetIndex(1); // Set the sheet to the second page.
    $sheet = $phpExcel->getActiveSheet();
    $sheet->setCellValue($cellKey,"Tea Sold as Of $date");
    $style = $sheet->getStyle($cellKey);
    $style->getFont()->setBold(true);
    
    $phpExcel->setActiveSheetIndex(0); // Set the sheet back to the first page, so the first page is what the user sees.
    
    Step 6: Save The File

    PHPExcel uses an object factory to create a writer that will write the spreadsheet you’ve built into the appropriate format. In this case I used "Excel5" because even very old spreadsheet programs can read it, so my report is available to the biggest demographic possible.

    // Write the spreadsheet file...
    $objWriter = PHPExcel_IOFactory::createWriter($phpExcel, 'Excel5'); // 'Excel5' is the oldest format and can be read by old programs.
    $fname = "TestFile.xls";
    $objWriter->save($fname);
    
    // Make it available for download.
    echo "&lt;a href=\"$fname\"&gt;Download $fname&lt;/a&gt;";
    
    Final Product

    The image below shows a partial screen shot of the final product built by the included sample code. It’s a two page spreadsheet, populated from the sample database and formatted with custom titles on each page:

    Conclusion

    Once the data from the database is in the PHPExcel object, you can use the other features of the PHPExcel class to perform addtional formatting, add more formulas, save it to different file formats and anything else that PHPExcel allows you to do.

    The MySqlExcelBuilder class could, for example, be extended to use the features of PHPExcel to populate an existing spreadsheet template with data from your MySQL database. Since PDO is the underlying database interface, the DSN in the constructor of MySqlExcelBuilder can be altered for other databases quite easily.

    If you have any questions or have run into any troubles, please let me know in the comments section below. Thank you so much for reading!


  • Permalink for 'Join the Nettuts+ Community on Google+'

    Join the Nettuts+ Community on Google+

    Posted: November 22nd, 2011, 9:39am MST by David Appleyard

    We’re excited to let you know that now, in addition to Twitter and Facebook, you can get involved with the Nettuts+ community over at Google+! We’ll be using Google+ to let you know about our latest tutorials, competitions, and Tuts+ news. Read on to find out more…

    What to Expect on Google+ Nettuts+ on Google+

    Through Google+, we’ll be publishing links to our new tutorials and articles, industry news, graphics and examples from our community, and lots more! It’s going to be an extension of the Nettuts+ site and community, in the same way we treat Twitter and Facebook.

    Don’t have a Google+ account? You can head over and create one here, or find out a little more about how it works.

    Add Nettuts+ to Your Circles (function() {var po = document.createElement("script"); po.type = "text/javascript"; po.async = true;po.src = "https://apis.google.com/js/plusone.js"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(po, s); })();

    Just use the button above to add Nettuts+ to your circles, so you don’t miss out on any of our new content. We look forward to seeing you on Google+!


  • Permalink for 'How to Inject Custom HTML and CSS into an iframe'

    How to Inject Custom HTML and CSS into an iframe

    Posted: November 21st, 2011, 2:59pm MST by Jeffrey Way

    Ever been to a site like JSBin, where you can write HTML, CSS, and JavaScript, and then see the results in a panel to the right? An iframe is how we can accomplish this task. In today’s quick tip, I’ll show you how to inject HTML and CSS into an iframe.

    Select 720p for optimal viewing.


  • Permalink for 'How to Create a Time Based CSS Style Sheet Switcher'

    How to Create a Time Based CSS Style Sheet Switcher

    Posted: November 21st, 2011, 12:29pm MST by Janet Wagner

    Style switchers have become a popular feature on websites these days. CSS style sheets allow a Web Designer to change the look and feel of a website with little effort. Some sites use “Day” and “Night” type of style switchers that automatically change the site theme based on the time of day.

    This tutorial shows you how to create a time based CSS style sheet switcher using PHP that lets you change multiple style sheets at once at specific times of the day. There’s also a little bit of jQuery UI thrown in just for fun!

    Why PHP instead of JavaScript?

    The one drawback to using PHP for a time based CSS style sheet switcher is that the time is based on either the web hosting server or on a “time zone” set in the script.

    When I was building my personal portfolio site, I created a time based style sheet switcher using JavaScript and jQuery. The time function of the script worked correctly. However, there was always a brief “flash” of the default style sheet when the web pages loaded.

    JavaScript heavy websites can have problems with conflicts between various JavaScript scripts. I decided to use PHP instead for the CSS style sheet switcher. Because PHP is server side, there were no JavaScript conflicts and the script worked as expected.

    The one drawback to using PHP for a time based CSS style sheet switcher is that the time is based on either the web hosting server or on a “time zone” set in the script. With JavaScript you can set time functions to be based on a user’s computer.

    Before We Begin

    If you are new to PHP, you need to set up and configure a server environment on your local computer (PHP files can not be viewed in a web browser). My personal preference is XAMPP. This article includes a few software options and basic instructions on how to set up a local server.

    Although you can use Notepad to create and edit PHP files, a code editor can be very helpful when writing web pages in PHP and other programming languages. Please refer to these articles for additional information on choosing a code editor:

    The code used in the tutorial creates a basic CSS style sheet switcher and you can view the demo here. The source files include two additional demos.

    Now, let’s get started!

    Step 1: Create the 1st CSS Style Sheet (Night)

    Create a CSS style sheet called style-1.cssand include the following code:

    
    /*  Default Styles
    --------------------------------------------------- */
    
    body {
    	margin: 0px;
    	padding: 0px;
    	background: url("../images/bokeh_2.jpg");
    	background-position: top left;
    	background-repeat: no-repeat;
    	background-attachment: fixed;
    	background-color: #666;
    	font-size: 20px;
    	font-family: Arial, Helvetica, sans-serif;
    	color: #fff;
    	text-align: left;
    }
    
    #wrapper	{
    	width: 965px;
    	margin: 0 auto;
    	position: relative;
    }
    
    a:link, a:visited, a:active {
    	color: #99ccff;
    }
    
    a:hover {
    	color: #0073ea;
    }
    
    .content_container_1	{
    	float: left;
    	width: 650px;
    	margin: 0px 0px 60px 0px;
    }
    
    p.main_description	{
    	margin: 5px 0px 50px 0px;
    	text-align: center;
    }
    
    /* Main Image
    --------------------------------------------------- */
    
    .main_image	{
    	background: url("../images/main_image_1.jpg");
    	background-repeat: no-repeat;
    	width: 630px;
    	height: 425px;
    	border: #fff solid 10px;
    	margin: 40px 0px 10px 0px;
    }
    
    /*  Tabs
    --------------------------------------------------- */
    
    #tabs p	{
    	font-family: Arial, Helvetica, sans-serif;
    	font-size: 20px;
    }
    
    a.tabs_link_1:link, a.tabs_link_1:visited, a.tabs_link_1:active {
    	text-decoration: underline;
    	color: #0073ea;
    	font-weight: bold;
    }
    
    a.tabs_link_1:hover {
    	text-decoration: underline;
    	color: #ff0084;
    	font-weight: bold;
    }
    
    #tabs .tabs_img	{
    	float: left;
    	background-color: #ddd;
    	padding: 8px;
    	margin: 0px 12px 0px 0px;
    }
    
    Step 2: Create the 2nd CSS Style Sheet (Morning)

    Open style-1.css and save it as style-2.css. Change the body background image from bokeh_2.jpg to bokeh_4.jpg. Change main_image_1.jpg to main_image_4.jpg.

    Step 3: Create the 3rd CSS Style Sheet (Afternoon)

    Use style-1.css or style-2.css to create a 3rd style sheet style-3.css. Change the body background image to bokeh_3.jpg and the main image to main_image_5.jpg

    Step 4: Create the 4th CSS Style Sheet (Evening)

    Create a 4th style sheet style-4.css. Change the body background image to bokeh_1.jpg and the main image to main_image_8.jpg

    For steps 2 through 4, feel free to change other elements like font colors and image borders. Instead of using the images provided in the source files, you can use your own images to create custom CSS styles.

    Step 5: Download jQuery and jQuery UI

    To show how the PHP script changes multiple style sheets at once, jQuery Themeroller Themes are being used to style the tabbed content area of the web page.

    Go to the jQuery UI Download Page and download the “Flick” and “Start” themes.

    Next, go to the official jQuery website and download jQuery.

    Step 6: The Markup

    Create a PHP file that includes the following code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    " [www.w3.org] <html xmlns=" [www.w3.org] xml:lang="en" lang="en">
    <head>
    
    <meta [http-equiv="Content-Type"] content="text/html; charset=iso-8859-1" />
    
    <!-- CSS style sheets -->
    <?php include("style sheets.php"); ?>
    
    <!-- jQuery / JavaScript -->
    <script type="text/javascript" src="js/jquery-1.6.3.min.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js">></script>
    <script type="text/javascript">
    	$(function() {
    		$( "#tabs" ).tabs();
    	});
    </script>
    
    <meta name="description" content="This demo uses PHP to change multiple CSS style sheets (Main CSS and jQuery UI Theme) at specific times during a 24 hour period. The timezone for this demo is set to Australia/Melbourne." />
    <meta name="keywords" content="time,based,css,stylesheet,switcher,php" />
    <title>Simple Time Based CSS Style Sheet Switcher</title>
    
    </head>
    <body>
    
    <!-- Begin Wrapper -->
    <div id="wrapper">
    
    <!-- Begin Content Container 1 -->
    <div class="content_container_1">
    
    <!-- Main Image Switches at Set Times -->
    <div class="main_image"></div>
    <p class="main_description">
    Main Image changes at the times set in PHP Script (Australia/Melbourne).
    </p>
    
    <!-- Begin Tabs Area -->
     <div id="tabs">
    	<ul>
    		<li><a href="#tabs-1">About Envato</a></li>
    		<li><a href="#tabs-2">Marketplaces</a></li>
    		<li><a href="#tabs-3">Tuts+ Network</a></li>
    	</ul>
    
    	<div id="tabs-1">
    	<p>
    	<img class="tabs_img" src="images/envato_1.jpg" width="300" height="195" alt="About Envato" />
    	Envato is a startup based out of Australia with people around the world and sites serving pages every second. We started in a living room in 2006 and have been steadily working to build our company into a world-class contender. Our background is creative, we love open source, we believe that work is about way more than just making money, and we're totally committed to making products that are awesome!
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [envato.com] target="_blank" title="Visit The Envato Website">Visit The Envato Website</a>
    	</p>
    	</div>
    
    	<div id="tabs-2">
    	<p>
    	<img class="tabs_img" src="images/marketplace_1.jpg" width="300" height="195" alt="Marketplaces" />
    	The Envato Marketplaces allow anyone to buy or sell digital goods like WordPress themes, background music, After Effects project files, Flash templates and much more. The marketplaces are home to a thriving community of over 500,000 users, authors and buyers and every day hundreds of new files are added.
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [themeforest.net] target="_blank" title="Visit the Theme Marketplace">Visit the Theme Marketplace</a>
    	</p>
    	</div>
    
    	<div id="tabs-3">
    	<p>
    	<img class="tabs_img" src="images/psdtuts_1.jpg" width="300" height="195" alt="Tuts+ Network" />
    	At Envato we're very passionate about education, that's why we've created one of the most popular networks of educational blogs around. Tuts+ serves up over 18 million pageviews a month across its many subsites on subjects like graphics, web development, audio production, iPhone development and motion graphics.
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [tutsplus.com] target="_blank" title="Visit Tuts+ Hub">Visit Tuts+ Hub</a>
    	</p>
    	</div>
    
    </div>
    <!-- End Tabs Area -->
    
    </div>
    <!-- End Content Container 1 -->
    
    </div>
    <!-- End Wrapper -->
    
    </body>
    </html>
    
    Step 7: PHP CSS Stylesheet Switcher Code

    Create a PHP file that includes the following code:

    <?php
    
    date_default_timezone_set("Australia/Melbourne"); // Set default time zone
    
    $time = date("H"); // Set the time in 24 hour format
    
    if (00 <= $time && $time < 07) // 12:00am to 7:00am   Night
    	{
    	echo
    '<link href="css/style-1.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    
    elseif (07 <= $time && $time < 12) // 7:00am to 12:00pm   Morning
    	{
    	echo
    '<link href="css/style-2.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    
    elseif (12 <= $time && $time < 18) // 12:00pm to 6:00pm   Afternoon
    	{
    	echo
    '<link href="css/style-3.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    
    else // all other hours   Evening
    	{
    	echo
    '<link href="css/style-4.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    
    ?>
    
    Breakdown of the Markup PHP Include for rel="stylesheet" Links

    The script for the CSS Style sheet Switcher is going to be contained in a PHP include file called stylesheets.php.

    A PHP include() statement includes and evaluates a specified file. The stylesheets.php include file is referenced by this code:

    <!-- CSS style sheets -->
    <?php include("style sheets.php"); ?>
    

    Because we are using a PHP script to change CSS style sheets at set times, the rel=”stylesheet” links will be generated by the PHP script.

    Reference jQuery and jQuery UI Libraries

    We need to make sure that the web page references the jQuery and jQuery UI libraries.

    Between the head tags of the web page the following code has been added:

    <!-- jQuery / JavaScript -->
    <script type="text/javascript" src="js/jquery-1.6.3.min.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script>
    
    Initialize jQuery UI Tabs

    This tutorial includes jQuery UI Tabs using the default functionality. The following code initializes the tabs:

    <script type="text/javascript">
    	$(function() {
    		$( "#tabs" ).tabs();
    	});
    </script>
    
    Container Div for jQuery UI Tabs
    <!-- Begin Wrapper -->
    <div id="wrapper">
    
    <!-- Begin Content Container 1 -->
    <div class="content_container_1">
    

    (Ending </div> tags for Wrapper and Content Container 1 are shown in the Code block for the Markup of the jQuery UI Tabs)

    Most of the jQuery UI Widgets are programmed to expand to 100% width of the content area where they are placed.

    The container div content_container_1 has been set to a fixed width of 650px in the CSS so that the tabbed content area does not expand the entire width of the screen.

    Main Image Markup

    In order for the main image to also be changed at set times using the PHP script, it needed to be included on the web page as a CSS background image.

    So instead of adding the image to the web page using markup like this:

    <img src="main_image_1.jpg" width="630" height="425" alt="Image" />
    

    It was added to the web page as a CSS background image of a <div> with the class “main_image”, like this:

    <!-- Main Image Switches at Set Times -->
    <div class="main_image"></div>
    <p class="main_description">
    Main Image changes at the times indicated.
    </p>
    
    Markup for the jQuery UI Tabs

    The below markup adds the tabbed content area that is powered by jQuery UI and has been styled using jQuery Themeroller Themes.

    <!-- Begin Tabs Area -->
     <div id="tabs">
    	<ul>
    		<li><a href="#tabs-1">About Envato</a></li>
    		<li><a href="#tabs-2">Marketplaces</a></li>
    		<li><a href="#tabs-3">Tuts+ Network</a></li>
    	</ul>
    
    	<div id="tabs-1">
    	<p>
    	<img class="tabs_img" src="images/envato_1.jpg" width="300" height="195" alt="About Envato" />
    	Envato is a startup based out of Australia with people around the world and sites serving pages every second. We started in a living room in 2006 and have been steadily working to build our company into a world-class contender. Our background is creative, we love open source, we believe that work is about way more than just making money, and we're totally committed to making products that are awesome!
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [envato.com] target="_blank" title="Visit The Envato Website">Visit The Envato Website</a>
    	</p>
    	</div>
    
    	<div id="tabs-2">
    	<p>
    	<img class="tabs_img" src="images/marketplace_1.jpg" width="300" height="195" alt="Marketplaces" />
    	The Envato Marketplaces allow anyone to buy or sell digital goods like WordPress themes, background music, After Effects project files, Flash templates and much more. The marketplaces are home to a thriving community of over 500,000 users, authors and buyers and every day hundreds of new files are added.
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [themeforest.net] target="_blank" title="Visit the Theme Marketplace">Visit the Theme Marketplace</a>
    	</p>
    	</div>
    
    	<div id="tabs-3">
    	<p>
    	<img class="tabs_img" src="images/psdtuts_1.jpg" width="300" height="195" alt="Tuts+ Network" />
    	At Envato we're very passionate about education, that's why we've created one of the most popular networks of educational blogs around. Tuts+ serves up over 18 million pageviews a month across its many subsites on subjects like graphics, web development, audio production, iPhone development and motion graphics.
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [tutsplus.com] target="_blank" title="Visit Tuts+ Hub">Visit Tuts+ Hub</a>
    	</p>
    	</div>
    
    </div>
    <!-- End Tabs Area -->
    
    </div>
    <!-- End Content Container 1 -->
    
    </div>
    <!-- End Wrapper -->
    

    The Menu “Tabs” are generated by an unordered list. The content sections are generated by <div> tags that have unique IDs that correspond to anchor links in the <li></li> tags.

    For example: <div id=”tabs-1″> corresponds with <a href=”#tabs-1″>

    Breakdown of PHP Stylesheet Switcher Code Set the Default Time Zone:
    date_default_timezone_set("Australia/Melbourne"); // Set default time zone
    

    The code date_default_timezone_set sets the default timezone used by all date/time functions in a script.

    If the script does not include date_default_timezone_set, then the web hosting server time will be used for all date/time functions in the script.

    Please refer to the List of Supported Timezones to find the appropriate timezone for your location.

    Newer versions of PHP incorporate “Daylight Savings Times” into the functionality of date_default_timezone_set. Some older versions of PHP do not take “Daylight Savings Times” into account.

    Set the Time in 24 Hour Format:
    $time = date("H"); // Set the hour in 24 hour format
    

    date(“H”) formats the local time/date in a 24-hour format of an hour, with leading zeros. Click Here to view information about the 24-hour clock.

    Breakdown of If, Elseif, Else Statement

    I’ve broken down the rest of the PHP code to show how the PHP script will function line by line. There are several functions being utilized in the code including:

    if
    if (00 <= $time && $time < 07) // 12:00am to 7:00am   Night
    	{
    	echo
    '<link href="css/style-1.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    

    If 00 (midnight) is Less than or equal to current time AND current time is Less than 07 (7:00am) Then the script will apply style-1.css and flick CSS style sheets.

    elseif
    elseif (07 <= $time && $time < 12) // 7:00am to 12:00pm   Morning
    	{
    	echo
    '<link href="css/style-2.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    

    If 07 (7:00am) is Less than or equal to current time AND current time is Less than 12 (12:00pm) Then the script will apply style-2.css and start CSS style sheets.

    elseif
    elseif (12 <= $time && $time < 18) // 12:00pm to 6:00pm   Afternoon
    	{
    	echo
    '<link href="css/style-3.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    

    If 12 (12:00pm) is Less than or equal to current time AND current time is Less than 18 (6:00pm) Then the script will apply style-3.css and start CSS style sheets.

    else
    else // all other hours   Evening
    	{
    	echo
    '<link href="css/style-4.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    

    If NONE of the conditions are met in the “if…elseif” statements, Then the script will apply style-4.css and flick CSS style sheets.

    Conclusion

    With CSS, you can create many different styles for your web pages. Using PHP, you can apply those styles dynamically to your website. Throw in a little jQuery UI, and your web pages will not only be fun for you to create, but fun for your visitors as well!

    If you have any questions about this tutorial, please ask them below, Thank you so much for reading!


  • Permalink for 'Python from Scratch – Create a Dynamic Website'

    Python from Scratch – Create a Dynamic Website

    Posted: November 19th, 2011, 2:32pm MST by Giles Lavelle

    We’ve covered quite a bit of Python in the previous tutorials in this Session. Today, we’re going to combine everything we’ve learned so far to build a dynamic website with Python.

    Prefer a Video Tutorial?

    Watch more video tutorials on YouTube.

    So, how do you get started creating websites with Python? Well, you could do it all yourself, and write a program that runs on a web server, accepting page requests and serving up responses in the form of HTML and other resources. However, that’s a lot of work, so why go to all the trouble when there are plenty of existing tools out there to do the job for you? These tools are called frameworks, and they’re what we’ll use today to create our website.

    Python Frameworks

    There are quite a few Python web frameworks, but here are some of the best:

    • Django – We’re going to use this today. It has a huge set of features, but remains simple to use. The documentation is also excellent, so if you get stuck, you’ll have the easiest time solving your problem with Django.
    • Grok – Another framework with a feature set that comes close to Django. If you decide you don’t prefer Django, this is a good alternative.
    • WebPy – A much more lightweight framework. It doesn’t have as many features, though it did power Reddit for a period of time!
    • TurboGears – Though previously having a reputation for poor documentation, TurboGears has improved substantially in the last year.

    A more comprehensive list can be found on the Python website if you’re in need of additional options. Today we’re going to set Django up for development on a local machine, and then build a simple blog. We’re also going to review the process of installing it on a remote web server.

    Installing Django

    We’ll be performing most of our work today in the Terminal. This should all work on Mac and Linux; however, if you’re running Windows, the process is somewhat different. A familiarity with the command line isn’t necessary if you’re only writing Python, though, if you’re planning on using Django, or running a dynamic website in general, it’s worth learning.

    Terminal Tutorials

    Consider reviewing these tutorials to get yourself up and running with the Terminal.

    Here are the commands you need to install Django. It’s not compatible with Python 3, so you’ll need to install version 2.7 or earlier to get it running.

        wget [www.djangoproject.com]     tar xzvf Django-1.3.1.tar.gz
        cd Django-1.3.1
        python setup.py install
    

    Next, we can optionally remove the install files.

        cd ..
        rm Django-1.3.1.tar.gz
    

    That should do it! Let’s test it out.

        python
        from django import get_version
        get_version()
    

    You should see ’1.3.1′. If you do, everything worked and Django is installed on your system. Congratulations! We’re ready to begin creating our site!

    Building our Blog

    We’re going to build a blog system today, because it’s an excellent way to learn the basics. First, we need to create a Django project.

    cd ~/Documents/Projects
    django-admin.py startproject FirstBlog
    cd FirstBlog
    ls
    

    What do each of these files do?

    • __init__.py tells Python that this folder is a Python package. We learned about these in the third lesson; it allows Python to import all of the scripts in the folder as modules.
    • manage.py isn’t actually part of your website; it’s a utility script that you run from the command line. It contains an array of functions for managing your site.
    • settings.py contains your website’s settings. Django doesn’t use XML files for configuration; everything is Python. This file is simply a number of variables that define the setting for your site.
    • urls.py is the file that maps URLs to pages. For example, it could map yourwebsite.com/about to an About Us page.

    Django refers to itself an MTV framework, which stands for Model Template View.

    Apps

    However none of these files on their own make a functional website. For that, we need Apps. Apps are where you write the code that makes your website function, but before we take a look at them, we need to understand a bit about Django’s design principles.

    First, Django is an MVC framework, which stands for Model View Controller. Django refers to itself an MTV framework, which stands for Model Template View. It’s a slightly different approach than MVC, but fundamentally, they’re quite similar. Anyhow, MVC is an architectural pattern that provides a method for structuring your projects. It separates the code that’s used to process data from the code that manages the user interface.

    Django subscribes to the DRY, or “Don’t Repeat Yourself” philosophy.

    Secondly, Django subscribes to the DRY, or Don’t Repeat Yourself philosophy, which means that you should never be writing code that performs a certain task more than once. For example, in our blog, if we wrote a feature that picked a random article from the archive, and implemented this feature on multiple pages, we wouldn’t code it again each time it was needed. We’d code it once and then use it on each page.

    So how does this relate to apps? Well, apps allow you to write your website in a DRY style. Each project, like the one we have here, can contain multiple apps. Conversely, each app can be part of multiple projects. Using the example from earlier, this means that if we made another site in the future that also needed a random page feature, we wouldn’t have to write it all over again. We could simply import the app from this project. Because of this, it’s important that each app serves one distinct purpose. If you write all the functionality of your site within one app, and then need to use part of it again later, you have to import it all. If you were making an eCommerce website, for example, you wouldn’t want to import all the blog features. However, if you make one app for the random feature and one app for the blog publishing system, you could pick and choose the bits that you require.

    This also means that within the site, the code is well organized. If you want to alter a feature, you don’t have to search through one massive file; you can instead browse to the relevant app and change it without worrying about interfering with anything else.

    python mangage.py startapp blog
    cd blog
    ls
    

    Again, we’ve got an __init__.py file to make it a package, and three other files: models, tests and views. We don’t need to worry about tests for now, but the other two are important. Models and Views are the M and V parts of MVC.

    In models, we define our data structures.

    If you’ve ever worked with PHP before, you might have used PhpMyAdmin to create your MySQL tables, and then written out your SQL queries manually in your PHP scripts. In Django, it’s much easier. We define all the data structures we need in this models file, then run a command and all the necessary databases are made for us.

    When you wish to access that data, you go via these models by calling method on them, instead of running raw queries. This is very helpful, because Django can use several database programs. We’re going to use MySQL today, because it’s the most powerful, and is what most hosts provide, but if we needed to switch to a different database in the future, all of the code will still be valid! In other languages, if you wanted to switch to SQLite or something similar, you would need to rewrite the code that accesses your database.

    In the views file, we write the code that actually generates the web pages. This ties all the other parts together. When a user types in a URL, it is sent by the urls script we saw earlier to the views script, which then gets relevant data from the models, processes it and passes it into a template, which finally gets served up as the page the user sees. We’ll take a look at those templates shortly. They’re the easiest part – mostly HTML.

    For a blog, we’ll need a table of posts, with several fields for the title, body text, author, the time it was written, and so on. A real blog would have comments, but that’s beyond the scope of today’s demo.

    from django.db import models
    
    class posts(models.Model):
        author = models.CharField(max_length = 30)
        title = models.CharField(max_length = 100)
        bodytext = models.TextField()
        timestamp = models.DateTimeField()
    
    MySQL

    These models are just a description. We need to make an actual database from them. First, however, we need MySQL running on our system. On an actual web server, this wouldn’t be a problem, because they usually have it preinstalled. Luckily, with a package manager, it’s easy to install. First, you need to install Homebrew and Easy Install

    brew install mysql
    easy_install mysql-python
    
    mysqld_safe --skip-grant-tables #let anyone have full permissions
    mysql -u root
    UPDATE mysql.user SET Password=PASSWORD('nettuts') WHERE User='root'; #give the user 'root' a password
    FLUSH PRIVILEGES;
    
    mysql -u root -p #log in with our password 'nettuts'
    CREATE DATABASE firstblog;
    quit
    
    python2.6 manage.py runserver
    

    When you reboot, MySQL won’t be running, so every time you need to do this in the future, run mysqld to start the server. You can then run python2.6 manange.py runserver in a new tab to start the development server.

    This command won’t run the server yet, it will just return an error. That’s because we need to configure our settings. Let’s take a look at settings.py.

    You need to change the database settings first. These begin on line twelve.

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
            'NAME': 'firstblog',                      # Or path to database file if using sqlite3.
            'USER': 'root',                      # Not used with sqlite3.
            'PASSWORD': 'nettuts',                  # Not used with sqlite3.
            'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
            'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
        }
    }
    

    If you try to run the server again, it should work, provided that you successfully installed MySQL. If you visit 127.0.0.1:8000 in your web browser, you should see the default Django page.

    Now let’s turn our Django site into a blog. First, we need to use our Models to create tables in the database by running the following command:

    python2.6 manage.py syncdb

    Every time you change your models, you should run this command to update the database. Note that this can’t alter existing fields; it may only add new ones. So if you want to remove fields, you’ll have to do that manually with something like PhpMyAdmin. Because this is the first time we’ve run the command, Django will set up all the default built in tables for things like the administration system. Just type ‘yes’ and then fill in your details.

    Now let’s set up the urls.py file. Uncomment the first line in the examples section, and change it to say url(r'^$', 'FirstBlog.blog.views.home', name='home') .

    Now, let’s create the views file to respond to these requests.

    from django.shortcuts import render_to_response
    
    from blog.models import posts
    
    def home(request):
        return render_to_response('index.html')
    
    Templates

    This index.html file doesn’t exist yet, so let’s make it. Create a folder, called templates in the blog app and save a file in it called index.html, which can simply contain “Hello World” for now. Then, we need to edit the settings file so Django knows where this template is located.

    Line 105 is where the section for declaring template folders starts; so adjust it, like so:

    TEMPLATE_DIRS = (
        "blog/templates",
        # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
        # Always use forward slashes, even on Windows.
        # Don't forget to use absolute paths, not relative paths.
    )
    

    If you run the server again and refresh the page in your browser, you should see the “Hello World” message. We can now begin laying out our blog. We’ll add some boilerplate HTML for the home page.

    <!DOCTYPE html>
    
    <html lang="en">
    
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="css/style.css">
        <link href="images/favicon.ico" rel="shortcut icon">
        <title>First Blog</title>
    </head>
    
    <body>
    
    <div class="container">
        <h1>First Blog</h1>
        <h2>Title</h2>
        <h3>Posted on date by author</h3>
        <p>Body Text</p>
    
    </div>
    
    </body>
    
    </html>
    

    If you save and refresh the page, you should see that the page has been updated with this new content. The next step is to add dynamic content from the database. To accomplish this, Django has a templating language that allows you to embed variables with curly braces. Change the middle section of your page to look like this:

    <div class="container">
        <h1>First Blog</h1>
        <h2>{{ title }}</h2>
        <h3>Posted on {{ date }} by {{ author }}</h3>
        <p>{{ body }}</p>
    
    </div>
    

    We can then pass in values to these variable placeholders from the views.py file by creating a dictionary of values.

    from django.shortcuts import render_to_response
    
    from blog.models import posts
    
    def home(request):
        content = {
            'title' : 'My First Post',
            'author' : 'Giles',
            'date' : '18th September 2011',
            'body' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam cursus tempus dui, ut vulputate nisl eleifend eget. Aenean justo felis, dapibus quis vulputate at, porta et dolor. Praesent enim libero, malesuada nec vestibulum vitae, fermentum nec ligula. Etiam eget convallis turpis. Donec non sem justo.',
        }
        return render_to_response('index.html', content)
    

    Save and refresh, and you should see that you’re now passing in content to a template from your views file. The final step is to get data from our database and pass that in instead. Luckily, we can do this all without SQL queries, using Django’s models. We need to add our blog app to our FirstBlog project by changing another setting. Go to INSTALLED_APPS on line 112, and add the

    'FirstBlog.blog',

    to the list.

    Then change views.py so it adds data from the database.

    from django.shortcuts import render_to_response
    
    from blog.models import posts
    
    def home(request):
        entries = posts.objects.all()[:10]
        return render_to_response('index.html', {'posts' : entries})
    

    Next, update the template to access this data.

    <div class="container">
        <h1>First Blog</h1>
        <hr />
        {% for post in posts %}
            <div class="post">
            <h2>{{ post.title }}</h2>
            <h3>Posted on {{ post.timestamp }} by {{ post.author }}</h3>
            <p>{{ post.bodytext }}</p>
            </div>
            <hr />
        {% endfor %}
    </div>
    

    Here, we can access all the data in our table in the views.py file, then select only the first ten entries. We pass this data into the template, loop through the entries and display the data with the HTML of our site. This won’t work just yet, because there’s nothing in the database. Stop the server and run:

    python2.6 manage.py syncdb
    

    This will add the new table for our posts to the database. Then, open a new tab and type:

    mysql -u root -p
    

    …type your password, hit enter, and execute:

    INSERT INTO blog_posts (author, title, bodytext) values ('Bob', 'Hello World', 'Lorem Ipsum');
    

    Return to the previous tab and run the server again. Refresh the page and you should see a blog post with the dummy content you just added. If you run the MySQL command a few more times, you should see more posts appear on the page when you refresh.

    Django’s Admin System

    The last thing we need to do today is review Django’s administration system. This is a really powerful feature of Django that lets you manage your site without writing any more code, as you would have to if you were creating a site from scratch. To enable it, we need to change a few settings. First, uncomment lines 4, 5, 13 and 16 within urls.py, so that you can actually access the admin page. Next, go to the INSTALLED_APPS section of settings.py and uncomment 'django.contrib.admin', and 'django.contrib.admindocs',. To let the admin control your posts table, create a new file called admin.py in the blog folder, and add the following lines:

    from django.contrib import admin
    from blog.models import posts
    
    admin.site.register(posts)
    

    Run python2.6 manage.py syncdb again to add the tables for the admin section, and restart the server.

    If you visit 127.0.0.1:8000/admin now in your browser, you should see a login page. Use the details you chose earlier when you first ran the syncdb command to log in. You should see a section, called Blog, with a subtitle for the posts table. You can use this to create, edit and remove blog posts with a simple interface.

    That’s all there is to do. You’ve just created a fully functioning, albeit simple, blog. To finish this lesson, we’re going to look at installing Django on a web server.

    Installing on a Web Server

    There are two types of web hosting, and which one you have will affect whether you can use Django. If you have shared hosting, you’re entirely at the mercy of your host.

    Many cheap web hosts don’t support Python. While PHP is nearly guaranteed, support for other languages often isn’t. You’ll have to check the control panel to determine if Python (and Django) are available. Obviously the process is slightly different with every host. Almost all hosting runs on Apache, and we can use it to host Django, using the mod_wsgi or mod_python Apache modules.

    Most web hosts run scripts in several languages using CGI. Django can run on FastCGI, and also, theoretically, on CGI, but this is not officially supported and would be far too slow for an actual production website. You’ll need to check if these are installed. They’re usually found under a heading, like “CGI and Scripting Language Support”.

    If you have VPS hosting, or are lucky enough to have a dedicated server, your life is much easier. Usually these come with Python preinstalled, and from there, you only need to follow the same steps we went through to get a local copy of Django running. If you don’t have Python, you can install it with a package manager. Your system may even come with Django.

    ssh root@example.com
    
    wget [www.djangoproject.com] tar xzvf Django-1.3.1.tar.gz
    cd Django-1.3.1
    python setup.py install
    

    Once you’ve installed Django on your server, upload the site you just made using any file transfer client. You can put the files anywhere, but keep them out of the public folder, or anyone will be able to see the source code of your site. I use /home for all my projects.

    Next, create a MySQL database, called ‘firstblog’ on your server and run syncdb again. You’ll have to create your account for the admin control panel again, but this is a one-time thing.

    If you try and run this, you might receive an error, and that’s because the settings for the server are different those on your local computer. You may need to change the database password within settings.py, but depending on your server configuration, you may also encounter other issues. Google is your friend in these situations!

    To run the server this time, the command is slightly different. You have to specify an IP address and port so that you can access the site over the internet.

    python manage.py runserver 0.0.0.0:8000

    If you visit your site in a web browser, on port 8000, you should see your site!

    Conclusion

    That’s it for this lesson…and our series. I hope you’ve learned a number of useful skills over these past five lessons, and that you’re ready to go on and learn even more Python in the future. If you like the look of Django, and wish to continue increasing your knowledge of the framework, here’s some additional tutorials on the subject.

    As always, I’m happy to discuss any questions about this tutorial or Python in general within the comments. Thanks for reading.


  • December 2011 (25 items) →