AndreasLagerkvist.com is Live!

Unless you're looking for something you know is on exscale.se I think you might wanna check out my new blog instead. Exscale is officially closed although I will keep it live at least a little longer.



The Latest

You've reached exscale.se, it's a site about web standards, CSS, JavaScript, some PHP and MySQL and occasionally i post a 3D-image. Below you'll find the 8 most recent articles, but check out the archives for old school programming stuff, funny youtube clips and more!


Bye, bye exscale!

Saturday, July 18, 2009

It's a bit overdue but I thought I'd write an "official" final post on exscale.se.

As you've probably noticed AndreasLagerkvist.com is live so when I have spare time I put stuff on there instead.

I've quit my job and will be moving to Thailand in a few months. Once I'm there and have chilled out for at least 2 months I thought I'd take some time to finally work on my own projects again :)

I've got a massive todo-list and prolly won't finish half of it, but here's some:

  • -Brush-up all the old exscale-styles and go live with them (even the horrible ones) (just for fun :)-
  • Fix quite a few annoying bugs with andreaslagerkvist.com
  • Finish aFramework's admin and debug modes as well as the drag-n-drop page-builder and the installer
  • Build:
    • aWiki
    • aWebShop
    • aForum
    • aGallery
  • Fine-tune every site's every module, give them all hijaxed admins etc
  • Create a site for aFramework, make sure everything from download to install to finished site runs smoothly on most systems and browsers and write good documentation
  • Do something fun with the 3d-engine.. been thinking about a "guide" for aFramework-sites.. kindof like Dustin Diaz's mosquito (click "Tour") only I'd do something with the 3d-engine... we'll see what happens here :)
  • Brush up some of the jquery plugins (color picker, image viewer, pixastic editor)

Also I've started playing around with a little more advanced coding (than html/css at least :) again. Really interested in getting into 3D and games again.

Depending on what I feel like in January I may skip the previous todo-list entirely and focus on this one:

  • Create an Arkanoid-type game from scratch in Java and OpenGL
  • Create a Pacman-clone in the same
  • Get a 3D-object and a flat ground rendered on the screen that can be moved with an input-device

After that we'll see. If I'm lucky I might have time to do all of it and still come home with a tan :)

Those are the plans. In the future; check out AndreasLagerkvist.com instead, that's where it's all happening ;)

Adieu!

Update

All the old styles have been added again. Most could do with some brushing up though...

A Modular Design Pattern

Friday, July 17, 2009

In this tutorial I will explain a very simple way to structure your website modularly.

Separating each part of the website into its own module-files makes it very easy to do updates, debug stuff and also makes adding some ajax-magic a piece of cake.

The directory structure

  • index.php
  • contact.php
  • mod/
    • header.php
    • navigation.php
    • footer.php
    • article-listing.php
    • contact-form.php
    • about.php
  • css/
    • general.css
    • layout.css
    • header.css
    • navigation.css
    • footer.css
    • article-listing.css
    • contact-form.css
    • about.css
  • js/
    • general.js
    • contact-form.js
Controllers

The files contained in the root-directory (index and contact) are the so called controllers. They control which modules go on which pages and are pretty much just a list of PHP-includes:

index.php

<?php
    $htmlTitle 
'Home page';
    
$bodyID 'index';

    include 
'mod/header.php';
    include 
'mod/navigation.php';
    include 
'mod/article-listing.php';
    include 
'mod/footer.php';
?>

Modules

If you look in mod/ you'll find the actual module-templates. Each module should be wrapped in a div with an ID corresponding to the module-name (#navigaion, #article-listing):

article-listing.php

<div id="article-listing">

    <?php foreach($articles as $article) { ?>
        <!-- POSH -->
    <?php ?>

</div>

Modular CSS

In css/ you'll notice that each module also has its own CSS-file. Every selector in a module CSS-file should start with the module's ID-name. So if you open footer.css, every selector should start with #footer. This is to ensure no general styling goes in the module-files.

There's also a general.css where generic styling (on simple element selector-level (h1 for example)) as well as general (CSS-)classes goes, and a layout.css that is kind of the "controller" for the module's design-layer (CSS) where every selector starts with a body-id (#index-page #article-listing {width: 40%; float: left;}).

And modular JS

Similarly, in js/, you'll find that each module that uses Javascript gets its own JS-file.

To make sure variable and function-names never colide, we use a similar name-spacing-standard in our JS where all the module's code goes in its own JS-object:

my-module.js

MyModule = {
    init: function() {
        this.doThisCoolThing();
        this.doTheOtherCoolThing();
        this.doThatAnnoyingThingThatBlinks();
    }, 

    doThisCoolThing: function() {}, 
    doTheOtherCoolThing: function() {},
    doThatAnnoyingThingThatBlinks: function() {}
};

MyModule.init();

It is recomended you compress and merge all your JS and CSS into one file each (all.js/all.css) as you want to keep the number of requests to a minimum to ensure a fast-loading website.

You can check out my javascript compressor as well as css compressor scripts for an easy way to merge and compress all css and js on the fly.

The benefits of modularity

The nice thing about structuring your code in a modular way like this is that you can run and render each module individually (by simply visiting /mod/my-module.php). Something very desirable if you like to hijax the functionality on your site.

The only thing that really differs from normal requests and ajax-requests is that you normally don't want to make any redirects, so I normally check to see if this is an ajax-request and, if so, act accordingly:

mod/contact.php

<?php
    $isAjax 
= isset($_SERVER['HTTP_X_REQUESTED_WITH']);

    
// ... other code

    
if(!$isAjax) {
        
header('Location: ...');
    }

    
// .... other code ...
?>

And I do all my ajax-requests through mod/:

contact.js

$('#contact form').submit(function() {
    $.post('mod/contact.php', {formData: formData}, function(data) {
        $('#contact').html($(data).html()); // the $(data).html()-trick makes only the innerHTML of the returned module go in the #contact-element. Since the contact-module includes a div#contact we don't want it in our current div#contact
    });
});

In this case we're hijaxing the form in the contact-module (#contact). Because the div#contact-element already exists we don't want to stick another div#contact in there, hence the $(data).html()-trick. This could also be done by if:ing the $isAjax in your template. I'm not sure if there are any performance-issues with doing $(data).html() rather than just data.

But it's not just ajax that's a breeze when you have a modular structure. Debugging and updating is also so much easier. When you know all your CSS for a particular module can be found in one file and one file only, and you also know that the styling in that file doesn't affect anything outside that module, you never have to worry about fixing an issue in one area, only to introduce a new one in another.

Pretty much the same obviously goes for the JS.

I've set up a very simple example-site with a basic ajax-call (using jQuery) that you can dig into if you feel like the article wasn't enough to get you started.

MVC Without a Framework

Friday, July 17, 2009

MVC is a programming design pattern that encourages separation of data, presentation and logic. Many frameworks are built on MVC but you don't necesarily need a framework to structure your code in an MVC manner.

This tutorial will try to explain how you can start using MVC today, with nothing but standard PHP. We will build a very simple blog/article publishing system. I will not cover comments or tags but after this article you should be able to easily add it yourself.

First I thought I'd try to, in a very basic way, explain each letter in the acronym. There's definitely more to it than this and I recommend you pick up a book on the area if you're really interested.

M

M in MVC stands for "model" and is supposed to be a model of your data. This could be anything from a database table to a set of files you treat equally. Basically, what we want to use the model for is anything that has to do with our data.

In the case of our blog we'll have one model called "Articles" which will handle everything that has to do with articles. Any time you want to edit, fetch, insert or delete articles you will use the model. There should be no (in this case) SQL-queries outside the model.

V

V stands for "view" and is a visual representation of your data. In the case of our articles this will be a list of the latest 5 or so articles in summary on the front-page and the whole article on each article page.

When doing web development most of your views will be HTML, but we'll create an RSS-feed as well and that will obivously be just that; RSS.

C

C stands for "controller" and its job is to either fetch, insert or delete data using the model, and then pass it on to the view so it can be displayed.

Depending on different user input the controller can do different things. For example, most blogs allow comments and the comments controller can display either the form for posting comments, or, after a comment has been posted, it might display a "Thank you"-text or similar.

The controller should handle all the logic behind a certain part of your application. The view should be nothing but presentation that is based on what the controller decides.

Modular Design

Many frameworks that use MVC treat one controller as one page on the site. Personally I prefer to structure my code in a more modular manner where each and every unique part of the page has one view and one controller. That way it can be moved around or deleted with a breeze.

Directory Structure

We'll put all our views and models in directories named the same. Each view will contain both the PHP logic and the HTML. This is a bit unorthodox but we'll still separate the logic from the presentation. In some cases the view won't even need any logic though, and in most cases only a few lines of model-calling is required. I've done it this way for simplicity but you could pretty easily separate the view and controller completely by providing a class or separate file with all the logic for each view.

For every different page on the site we'll create a very simple PHP-file in the root-directory that does nothing but include views. We'll only need 3 pages for our super-simple blog: home-page (displays the latest 5 articles), articles-page (displays all articles), article-page (displays one article).

Here's a list of all the dirs and files we'll create:

  • models
    • articles.php # the articles model - handles all communication with the articles table in the database
  • views
    • header.php # the header - contains all the stuff that's common to all page's heads
    • footer.php # the footer - contains all the stuff that's common to all page's foots
    • articles.php # the articles view - displays more than one article
    • article.php # the article view - displays one article
    • articles-rss.php # the articles RSS feed
  • index.php # the home-page
  • article.php # each article-page
  • articles.php # list of all articles

The Articles Database Table

....

The Articles Model

We'll wrap the articles model in a class called Articles. We'll create a bunch of static functions for everything we ever want to do with articles. We don't have to come up with everything now, it's OK to go back and fill this with functions as you need them. I've seen models that are several thousand lines of code :)

class Articles {
    /**
     * getArticles
     *
     * Retrieves articles based on params
     * 
     * @param $sort String - which column-name to sort the results by
     * @param $order String - in which order to sort them ('ASC' or 'DESC')
     * @param $start Int - where to start fetching articles from
     * @param $limit Int - how many articles to fetch
     * @returns $articles Array || false - an array of all articles or false if no articles matched the criteria
     **/
    public static function getArticles ($sort = '1', $order = 'ASC', $start = 0, $limit = 1000000000) {
        $articles = array();
        $qry = '
            SELECT 
                * 
            FROM 
                articles 
            ORDER BY 
                ' . mysql_real_escape_string($sort) . ' ' . mysql_real_escape_string($order) . ' 
            LIMIT
                ' . mysql_real_escape_string($start) . ' ' . mysql_real_escape_string($limit) . ' 
        ';

        $res = mysql_query($qry) or die(mysql_error() . $qry);

        if (mysql_num_rows($res)) {
            while ($row = mysql_fetch_assoc($res)) {
                $articles[] = $row;
            }

            return $articles;
        }
        else {
            return false;
        }
    }

    /**
     * getArticleBySlug
     *
     * Retrieves one article based on slug (URL)
     * 
     * @param $slug String - the article's slug
     * @returns $article Array || false - article array or false if no article existed
     **/
    public static function getArticleBySlug ($slug) {
        $qry = '
            SELECT 
                * 
            FROM 
                articles 
            WHERE
                slug = "' . mysql_real_escape_string($slug) . '"
            LIMIT 1
        ';

        $res = mysql_query($qry) or die(mysql_error() . $qry);

        if (mysql_num_rows($res)) {
            return mysql_fetch_assoc($res);
        }
        else {
            return false;
        }
    }

    /**
     * deleteArticle
     *
     * Deletes an article based on ID
     * 
     * @param $id Int - the article's ID
     **/
    public static function deleteArticle ($id) {
        mysql_query('DELETE FROM articles WHERE articles_id = ' . mysql_real_escape_string($id));
    }

    /**
     * updateArticle
     *
     * Updates an article based on ID
     * 
     * @param $id Int - the article's ID
     **/
    public static function updateArticle ($id) {
        # Homework :)
    }

    /**
     * insertArticle
     *
     * Inserts a new article
     * 
     * @param $article Array - An article array
     **/
    public static function updateArticle ($article) {
        # Homework :)
    }
}

As you can see, with this class in our hands we can do everything we need to do with our articles. If we want the latest 5 articles we'll simply go Articles::getArticles('pub_date', 'DESC', 0, 5); and if we want the article on /test-article/ we'll simply go Articles::getArticlesBySlug('test-article');

Like I said, you can add more functions to this class any time you need to do something new with articles (like getArticlesByTagSlug() or getMostCommentedArticles() etc etc).

The Views

Like I mentioned before most of our views will be pure HTML but they'll also contain the necesary logic required to display their contents.

Header & Footer

These will contain the HTML that will be displayed on each and every page. Typically the html, head and body elements but also our logo and copyright-information.

Header

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

    <head>

        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <meta http-equiv="Content-Style-Type" content="text/css" />

        <meta name="author" content="You" />
        <meta name="copyright" content="Copyright (c) 2010 You" />

        <link rel="alternate" type="application/rss+xml" title="articles" href="views/articles-rss.php" />
        <link rel="stylesheet" type="text/css" media="screen,projection" href="css/style.css" />

        <title>My Blog</title>

    </head>

    <body>

        <div id="wrapper">

            <div id="header">

                <h1><a href="/">MyBlog.com</a></h1>

                <p>Just another MVC blog</p>

            </div>

Footer

            <div id="footer">

                <p>Copyright &copy; 2010 You</p>

                <ul>
                    <li><a href="#" title="Top of Page">Top</a></li>
                    <li><a href="#" title="Get Firefox!">Firefox</a></li>
                    <li><a href="#" title="Valid XHTML">XHTML</a></li>
                    <li><a href="#" title="Valid CSS">CSS</a></li>
                </ul>

            </div>

        </div>

    </body>

</html>

These two files will be included first and last on every page. As you can see they're nothing but pure HTML. No PHP logic needed here.

The Articles View

The articles view will however require some logic. Like I mentioned before we'll still separate the PHP and HTML. If you like you could move all the PHP in the top to its own file in a new directory called controllers/ and include that instead of having it in the same file like me.

<?php
    
# The controller...
    
if ($homePage) {
        
$articles    Articles::getArticles('pub_date''DESC'05);
        
$title        'The Latest Articles';
    }
    else {
        
$articles    Articles::getArticles('pub_date''DESC');
        
$title        'All Articles';
    }

    
# The view...
?>
<?php 
if (count($articles)) { ?>
    <h2><?php echo $title?></h2>

    <ul>
        <?php foreach ($articles as $article) { ?>
            <li>
                <h3>
                    <a href="article.php?slug=<?php echo $article['slug']; ?>">
                        <?php echo $article['title']; ?>
                    </a>
                </h3>

                <p><small><?php echo $article['pub_date']; ?></small></p>

                <p><?php echo substr($article['content'], 0200); ?></p>
            </li>
        <?php ?>
    </ul>
<?php } else { ?>
    <h2>No Articles/h2>

    <p>Sorry no articles were found.</p>
<?php ?>

The Article View

<?php
    
# Make sure ?slug= is set
    
if (isset($_GET['slug'])) {
        
$article Articles::getArticleBySlug($_GET['slug']);

        
# If it's not a valid slug - die
        
if (!$article) {
            die(
'FAIL');
        }
    }
    
# Else die
    
else {
        die(
'FAIL');
    }
?>
<h2><?php echo $article['title']; ?></h2>

<p><small><?php echo $article['pub_date']; ?></small></p>

<p><?php echo $article['content']; ?></p>

The Articles RSS View

...

The Different Pages

The different pages (or files in root) will simply include the views they need to display the page.

The Home Page

<?php
    
include 'views/header.php';

    
$homePage true;
    include 
'views/articles.php';

    include 
'views/footer.php';
?>

The Articles Page

<?php
    
include 'views/header.php';
    include 
'views/articles.php';
    include 
'views/footer.php';
?>

The Article Page

<?php
    
include 'views/header.php';
    include 
'views/article.php';
    include 
'views/footer.php';
?>

Moving

Friday, July 17, 2009

I've been hard at work during my vacation in getting aFramework v3 and aBlog v3 ready so that I can finally go live with andreaslagerkvist.com.

I've also decided not to move all the existing content from exscale.se to al.com but rather start from scratch.

Exscale.se is quite old and there's plenty of crap on it so I think it's best to simply turn off comments and let exscale.se rest.

I may rewrite some of the more popular articles on al.com and redirect them. All the jQuery-plugs will get their own page on al.com and most of the jQuery-articles on exscale will be redirected.

Hope to see you at my new home; AndreasLagerkvist.com.

Laters!

Kukk3D - Javascript 3D Engine

Thursday, April 30, 2009

I had so much fun playing around with canvas when I built the Pixastic Editor that I decided to port my really old 3D-engine, Kukk3D, to JS.

Kukk3D
Click the image to view a demo

At the moment it's really basic even though it has support for faces (something that the old one never had) as well as lines and vectors.

You can add any type of object you like to the scene, move it around and re-render it. To animate you'd wanna do this X times per second, usually through a setTimeout.

A basic example:

<canvas id="kukk3d"></canvas>

<script type="text/javascript">
// Initiate the engine, pass in the canvas-ID and set width and height
Kukk3D.init('kukk3d', 640, 480);

// Create an object
// You can create any object you like or use one of the presets in objectSkeletons
var cube = Kukk3D.addObject(Kukk3D.objectSkeletons.cube());

// Now that the scene contains something, let's render it
// You can pass in a color-object as the only argument to render
// in order to fill the scene with a background-color
Kukk3D.render({r: 0, g: 0, b: 0, a: 1});

// To animate we simply move about the object and re-render
// the scene in a setInterval that runs every 50 ms
setInterval(function () {
    cube.rotation.y += 2;
    cube.rotation.z += 1;
    Kukk3D.render();
}, 50); // 50 ms = 20 fps
</script>

What you reckon?

jQuery Pixastic Editor

Friday, April 17, 2009

I started playing around with the Pixastic JS Library a few days ago and thought it was really cool.

For those that don't know it's a JS library that allows you to apply different effects to images using the canvas)-element.

So, naturally I had to create a jQuery plug-in that wraps all this cool functionality in a neat little package :)

jQuery Pixastic Editor

The jQuery Pixastic Editor can be applied to any image in your document and inserts a completely stylable toolbar next to the image in question.

Have a look at an example

As usual I've set up a simple example-page, please have a look at the source for how to implement it. It requires a few other jQ-plugs and the options-form works best if you have the UI slider installed as well.

Without some sort of server-side script it's not possible to save the altered image as a new file, but the plug-in allows the user to click the modified canvas to open its dataURL in a new tab which allows him to then use the browser's save-functionality to save the image to their local machine.

It's dynamic like hell :)

The toolbar is automatically generated from all the actions currently in Pixastic.Actions. This means that your can download your own build of Pixastic and the plug-in will automatically adapt to whatever effects you've chosen.

Most of the effects require the you to set certain options, to avoid hard-coding each of the options for every effect I wrote a little PHP-script that parses the Pixastic website for information about each effect. When a new effect is added I run the script again and get the latest updates.

This means, however, that the options-form isn't exactly tailor made. Some of the options could very well be converted to drop-downs for usability, but it'll have to wait till next release.

I do look for certain things in the description of the option though like for example if anything like "X to|and Y" occurrs in the text I interpret that as min and max values for the option.

Any option with a min and max-value will get a jQuery UI Slider inserted beneath it (but only if the user of the plug-in has UI Slider installed).

Also, if the string "defaults to Z" occurrs I set Z to the default-value for that option.

I could (and will) probably solve the drop-down issue by looking for something like "one of "foo", "bar" and "baz"" as that is how the author of Pixastic most commonly describes options with several possible values.

Finally

There are a few more features I haven't mentioned like different styles etc also it's highly in beta and a lot could be added but do have a look and let me know what you think.

Oh and I've only tested it in FF3.

Laters!

  • Comments are off
  • Filed under jQuery

jQuery Drag to Select Plug-in

Monday, April 06, 2009

Use this plug-in to allow your visitors to select certain elements by dragging and dropping a "select box".

jQuery Drag to Select

It works very similar to how most OS:es allow you to select files and folders.

I've set up a simple demo, please check the source-code for the different options. It's still in semi-beta.

All my plug-ins will be re-released on andreaslagerkvist.com once it's finished (right now I'm pretty much just waiting for PHP5.3 to be released).

Now with Ads!

Thursday, March 19, 2009

As you can see, unless you've got adblock installed, which you probably do.. :P, exscale.se has now got ads!

Most of the styles look like shit with the ad because it's too wide, but kubrick and aframework look fine.

AndreasLagerkvist.com is almost finished (although I don't think it'll be live for another few months) so I'm preparing to lay exscale to rest and the ads are one step in my plan towards becoming a millionaire without doing shit.



Post It

From June 02 to April 23

  1. Mogrify is what you're looking for if you want to convert multiple images to multiple other images in ImageMagick
  2. Tommorrow, finally, the inFamous demo will be friggin availble on PSN!! Suweeeeeeeeet
  3. Fuck canvas is cool, I've started playing around with old 3D-shit again :)

October 2014

S M T W T F S
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31


Recent Comments

  1. Vlad on A follow-up to "An alternative to div overlays":
    I'll try this.....
  2. Steve on jQuery Live Ajax Search Plug-in:
    This is a great script but I've got...
  3. Frank on jQuery Live Ajax Search Plug-in:
    Hey, sounds like a great plugin! I ...
  4. Andreas on jQuery Drag to Select Plug-in:
    @Paul - I didn't take into account ...

Style Switcher

The style switcher allows you to change the look and feel of exscale.se.
Only CSS and JavaScript are changed. The XHTML stays the same.

For more information about the styles, check the styles page.


Categories


Random Quote

conwincdence, i think not. - christus11


Random Images




Answer This!

Do you find the "scroll-pagination" annoying? (If you don't know what it is, scroll to the bottom of the first-page)


Blog Roll