Git Kinda’ Sucks

So, another “kinda sucks” article from me. This time, I’m taking on Git. I’m sure Git is wonderful for all of the companies that have adapted it and has dealt with its constraints and difficulties. Ask anyone who’s picked up Git after they’ve been used to SVN, or other repository. They will most likely tell you that it was difficult to implement, but now they’re happy that they spent the time to learn it.

What exactly was gained from it, other than for the sole purpose to learn something new? Nothing. I’ve picked up Git some time ago on one of my projects, and I was battling with it. It would fight me. Pull, push, commit, on and on. It just seemed like more ways one could screw up, that’s all.

SVN did everything I ever needed for my projects, and I have several projects, all with massive code bases, and some of which I run from multiple areas, and work with multiple developers. So, I gave Git another try when one of the team members I worked with on a project introduced it. He also introduced SASS at the same time. Let me tell you, for someone that knows their LAMP stack all too well, introducing all these bells and whistles makes you feel pretty stupid. Conflicts and overwrites became huge issues because the other team members weren’t told that SASS was going to be used, and no one mentioned that designers are going to change template code.

Don’t believe me? Check out others who are upset about Git as well:
http://steveko.wordpress.com/2012/02/24/10-things-i-hate-about-git/

…and the rebuttal:
http://www.tylerbutler.com/2012/08/ten-things-steve-bennett-hates-about-git/

Check out the first comment made by Steve Bennett, the writer in the first link.

In the end, it’s not about the technology that you use, it comes down to how well you use the technologies that you currently know. And I’ve always said the following two things, and follow them religiously:

1. If it ain’t broke, don’t fix it.
2. Stop trying to re-invent the wheel.

They pretty much say the same thing. It’s the same argument when it comes to using OOP for a web project. That’s for a later discussion. Check out the reason I made my own “opened framework” here.

PS. I really think someone invented Git to make SVN users much happier with their repository handling.

I’ve been saying this all along… Lazy programmers make for bad code

A link to an article about why code these days is so bloated.

I’ve been saying this for so long. Running a 3 mile race in 1 mile is not going to make you a faster athlete. It will weaken you as a performer. Get your ass off the couch, do the work, the right way, and always consider performance. Or, you get what’s coming to you. Adding frameworks and shortcuts to your development will only make you hurt later on.

Thoughts?

A New Way of Programming AJAX Style

As a programmer / web developer, I’ve been exposed to AJAX since before it was popular in jQuery. I remember creating my own $.ajax(); functions using XMLHTTP Requests, and other complicated javascript code and functions.

When exposed to jQuery, why reinvent the wheel? However, implementing the code to my current applications and websites was not that easy though. I wanted to create a sort of a system to integrate into a web app. Something that works for me. After many iterations, I came up with the following:

Where it all began

We need to trap the clicks to our app actions. In doing so, let’s look at the action buttons.

1
2
3
<body>
    <a href="#" class="btn" id="buttonone">Click Here</a>
</body>

And now, for the JS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function(){
    $(document)on('click','.btn',function(e){
        // This makes sure we don't follow through on the click.
        // In essence, we cancel the initial click.
        e.preventDefault();
        // Now we make an ajax call.
        $.ajax({
            url: '/ajax/buttonactions.php?action=actionone',
            success: function(data) {
                // and we output our results
                console.log(data);
            }
        });
    });
});

And our complementing PHP action file.

1
2
3
4
5
6
7
8
9
10
11
12
// To make sure we set our action
$action = isset($_GET['action']) ? $_GET['action'] : '';

// call the function passed in from the ajax call
call_user_func($action);

// the function of the same name as the parameter
// as passed in from AJAX call.
function actionone() {
    // data to return
    return "data is back";
}

We don’t know what we’re going to do with our data yet, so let’s make it make some sense. We would like to return a JSON object from our PHP, because inside the JSON object, we can pass structured HTML, as well as other JSON data to be used by JS.

Our PHP has been updated with the following (Notice the JSON Encoded array returned at the end):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// To make sure we set our action
$action = isset($_GET['action']) ? $_GET['action'] : '';

// call the function passed in from the ajax call
call_user_func($action);

// the function of the same name as the parameter
// as passed in from AJAX call.
function actionone() {
    // data to return
    $retVal = array(
        "error" => false,
        "message" => "Data is back!"
    );
    return json_encode($retVal);
}

And now, to deal with the data on JS side. Make our AJAX call be of dataType JSON. We check to see if the data returned has the error variable equal to true or false. If false, continue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$(document).ready(function(){
    $(document)on('click','.btn',function(e){
        // This makes sure we don't follow through on the click.
        // In essence, we cancel the initial click.
        e.preventDefault();
        // Now we make an ajax call.
        $.ajax({
            url: '/ajax/buttonactions.php?action=actionone',
            dataType: 'JSON',
            success: function(data) {
                // and we output our results
                if (!data.error) {
                    console.log(data.message);
                } else {
                    console.log('data return error');
                }
            }
        });
    });
});

But this is not too much fun. All of the processing and rendering would have to happen on the JS side if all we return is JSON data. Let’s put things in arrays, and nest them for future use. Also, use our Output Buffer to do the work for rendering things.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
...
function actionone() {
   
    $htmlToBeReturned = '';
    ob_start();
    ?><div>This is a block of HTML!</div><?php
    $htmlToBeReturned = ob_get_contents();
    ob_end_clean();
   
    // data to return
    $retVal = array(
        "error" => false,
        "message" => "Data is back!",
        "htmls" => array(
            "#buttonone" => $htmlToBeReturned
        )
    );
    return json_encode($retVal);
}
...
?>

Notice how we are returning HTML content inside our JSON object. It works really well too. json_encode takes care of everything for us. Also notice how we put our HTML return code inside another array called “htmls”. This is a great way to handle multiple HTML blocks that require changing. The great part about this is that you’re returning all of your data with one HTTP Request, one database call, and you’re manipulating multiple DOM blocks / elements. Another notice is the htmls object will contain the “selector” to be changed in the front end. You can have a string of these selectors, specific selectors, or a group of selectors, just like jQuery.

Our new JS code will look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
            success: function(data) {
                // and we output our results
                if (!data.error) {
                    console.log(data.message);
                    for ($html in data.htmls) {
                        $($html).html(data.htmls[$html]);
                    }
                    $('body').append();
                } else {
                    console.log('data return error');
                }
            }
...

And now we see how easy it was to manipulate the DOM via ajax. You can improve on this model by templetizing the rendering to be able to re-use the same tempalte, you can add data objects to the click element and pass them in as post parameters, etc.

This is how we templetize the rendering of the HTML:

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
<?php
...
function actionone() {
   
    $htmlToBeReturned = '';
    ob_start();
    renderHtmlBlockOne();
    $htmlToBeReturned = ob_get_contents();
    ob_end_clean();
   
    // data to return
    $retVal = array(
        "error" => false,
        "message" => "Data is back!",
        "htmls" => array(
            "#buttonone" => $htmlToBeReturned
        )
    );
    return json_encode($retVal);
}
...
function renderHtmlBlockOne() {
    ?><div>This is a block of HTML!</div><?php
}
...
?>

You can move the render functions inside a file to be included from anywhere so you can avoid duplicate render code.

Let’s make the click dynamic.

1
2
3
<body>
    <a href="#" data-action="actionone" class="btn" id="buttonone">Click Here</a>
</body>

And adjust the AJAX call to fit in any action:

1
2
3
4
...
        var $this = $(this);
        var $action = $this.attr('data-action');
...

We cached the clicked object so we don’t have to constantly refer to it via jQuery.

And the url:

1
2
3
4
5
...
        $.ajax({
            url: '/ajax/buttonactions.php?action='+$action,
            dataType: 'JSON',
...

Now, your only worries are to make sure that you assign the data-action to the clicked element to call the proper action in PHP. HTML -> JS -> PHP -> back to JS -> back to HTML. Pretty clever, huh? Input -> controller -> model -> controller -> output.

And now, for the promised bells and whistles of passing data through data attributes. We already passed in one data attribute, the action, now, we just have to add more data, and change the type of the AJAX call to post.

1
2
3
<body>
    <a href="#" data-action="actionone" data-data="id=1&type=active" class="btn" id="buttonone">Click Here</a>
</body>

In the code above, we pass in a string of data that can be dynamically generated when generating the page with PHP. In essence:

1
2
3
<body>
    <a href="#" data-action="actionone" data-data="id=<?php echo $id; ?>&type=<?php echo $type; ?>" class="btn" id="buttonone"><?php echo $actionTitle; ?></a>
</body>
1
2
3
4
5
...
        var $data = $this.attr('data-data');
...
            type: 'POST'
...

And in our PHP code,

1
2
3
4
5
6
<?php
...
    $id = $_POST['id'];
    $type = $_POST['type'];
...
?>

And that’s it. You can always improve on the code, but this is the general idea to keep things simple and expandable.

The HTML File:

1
2
3
<body>
    <a href="#" data-action="actionone" class="btn" id="buttonone">Click Here</a>
</body>

The JS file, assuming you’ve loaded jQuery:

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
$(document).ready(function(){
    $(document)on('click','.btn',function(e){
        // This makes sure we don't follow through on the click.
        // In essence, we cancel the initial click.
        e.preventDefault();
        // Now we make an ajax call.
       
        var $this = $(this);
        var $action = $this.attr('data-action');
        var $data = $this.attr('data-data');
       
        $.ajax({
            url: '/ajax/buttonactions.php?action='+$action,
            dataType: 'JSON',
            type: 'POST'
            success: function(data) {
                // and we output our results
                if (!data.error) {
                    console.log(data.message);
                    for ($html in data.htmls) {
                        $($html).html(data.htmls[$html]);
                    }
                    $('body').append();
                } else {
                    console.log('data return error');
                }
            }
        });
    });
});

And the AJAXed PHP code:

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
32
33
34
35
36
<?php
// To make sure we set our action
$action = isset($_GET['action']) ? $_GET['action'] : '';

// call the function passed in from the ajax call
call_user_func($action);

// the function of the same name as the parameter
// as passed in from AJAX call.
function actionone() {

    $id = $_POST['id'];
    $type = $_POST['type'];
   
    $htmlToBeReturned = '';
    ob_start();
    renderHtmlBlockOne();
    $htmlToBeReturned = ob_get_contents();
    ob_end_clean();
   
    // data to return
    $retVal = array(
        "error" => false,
        "message" => "Data is back!",
        "htmls" => array(
            "#buttonone" => $htmlToBeReturned
        )
    );
    return json_encode($retVal);
}
...
function renderHtmlBlockOne() {
    ?><div>This is a block of HTML!</div><?php
}

?>

Happy coding!

What Makes a Solid Web Dev. Team?

Or for that matter, what makes a solid software development team? Let’s start with the product in mind. Whenever you look at a product, you really need to understand its purpose. Every team member has to. It’s a requirement, I think. You can’t just black box everything.

The Basics:
This is your fire team!

For starters, you need a solid squad. Yes, like in the military. You need highly trained specialists in 4 different areas:

  • Design
  • UI/UX
  • Product
  • Dev

With those four roles in mind, yes, you can have cross overs. A designer can do UI, but not as well as a specialist in UI.

Let’s see the roles as they play out:

Product: The key role in understanding what they product is, and why it will be useful to the audience. A product owner has to be an awesome communicator. He has to explain to design why certain things will be added, removed, or modified. He has to be sharp when it comes to technology usage. Has to understand SEO requirements, and the most important, has to keep the product simple enough for the end user. The product most likely will have to have an added benefit, not increase the workload of the end users. Need marketing? Someone to put out fires? Talk to the public? This is your guy! There could be several people playing a few roles on the product team, but essentially, product means business.

UI/UX: User Experience is what will make the product work for the user, not against. Working closely with the product owner, the UI specialist has to understand that red buttons don’t work, orange ones do, but not too many on one page. Place the OK and Cancel button far apart so the end user doesn’t have an “accidental” click. UI also comes in very handy for mobile devices where a touch of a small button could spell disaster. Keeping buttons consistent, such as OK and Cancel pop ups is pretty crucial to end user experience. It makes the end user more comfortable if they see the same flow all over the site instead of having Yes and No buttons appear from time to time, unless there’s a logical reason to use them. All this and more in the day of a UI/UX Developer.

Designer: Having a creative person on your team, keeping up with the latest trends and designs is great. Everyone is using the Windows 8 Metro theme because it’s nice, but also because it’s light for the web. Simple colors, non rounded corners, no drop shadows or gradients all make for a quick loading site. Little white icons on top can be placed in a sprite that only loads once, or can be included in as a special font. In any case, this guy needs to be able to provide awesome designs, and great looking interfaces, without sacrificing speed or ease of use for end users.

Developer: Last, but definitely not least, the guy or guys to glue it all together, the developer. This is your heavy machine gunner. He carries over all of the requirements and glues them together in a nicely and smoothly working product. He’s the Goldie Locks of the team. There has to be a balance of speed, performance, reliability, maintainability, and of course, design, UX and many more factors. This team can consist of other sub specialists depending on your application requirements. Maybe a server guy, with a database guy, a back-end server-side script developer and a front-end specialist to handle all of the bells and whistles. Very rarely will you find someone with all these experiences.

So, now you have your fire team armed and ready, locked and loaded, locked cocked and ready to rock. Set your missions, and go out there and conquer ground! Get an idea going, build a start-up, get funding and take over the world!

OK Maya adding web design services…

I’ve been asked a lot lately to do websites for several of my friends. So, I figure, I already know how to make websites, why no help them out? I will keep everyone posted on the website I will be building. Meanwhile, visit the Portfolio page to see all, well, most of my current projects.

Want pricing? Consider the following. No two websites are ever the same. So, no pricing is ever the same. But, I did come up with a complex plan of showing you a simple table of prices that can keep it affordable for you and keep food on my table. Check out the pricing table here.

Successfully completed the “framework”

The reason I put it in quotes is because it’s not really a framework. It’s an open ended solution for anyone that wants a working website out of the box, ready with an admin section, credentials for admin and users, search based on parameters and zip code geo locations, and pagination.

So, basically, what inspired me to scrap what I had and redo everything from scratch, and go back to the basics was the idea of too much complexity. I was digging myself deeper and deeper into my own code, limiting myself to certain rules, when I know that PHP should never be limited to anyone’s design.

So, I came up with Clean PHP, read about it here:

http://okmaya.com/clean-php/clean-php-step-1/

This is the first time in my life that I feel reassured that I can really program, and anyone that claims that OOP belongs to web development and it’s crucial, is fooling themselves.

I have nothing against OOP in its place, like console games and desktop applications, but web dev is completely different. Apples and oranges.

Read up on the clean php pages and tell me I’m wrong. But make sure you read it first. Let’s look at it this way:

OOP for console games:

  1. Game Loads (takes some games 5 minutes to create objects in memory)
  2. Those objects are in the game for the entire life of the program, or level, that’s why you see loading bars at the start of every level.

OOP For websites:

  1. Now imagine coming to a website where you have to wait even 30 seconds for every page to load because it has to build objects. Just doesn’t make any sense.
  2. Why build objects on every page load, when all the objects are going to be gone once the page is loaded anyway?
  3. It’s like building a stock car at the start of every race only to completely take it apart at the finish line. Pointless.

Anyway, enough of my ramblings. I’m proud of the work I’ve put into this little package. I say little because at less than 80K, it kicks the crap out of any MVC OOP Framework out there.

  • Note to OOP Web Devs. Stop being lazy and learn to actually program. 😉

Framework maturing

The current framework is being used in an application inspired by my son. It seems to hold up well. One of the reasons this MVC framework is better is because it uses controllers at the model and view level.

Pre-thoughts…

Just remember, we’re building a website. Which means that each webpage is its own island. Web pages are supposed to be script, not objects. We’re not developing a desktop application. So, with that said, remember, we’re building this procedurally.

First, the .htaccess file. This is the very first entry point in every page. We need to specify some routing. Basically, if the file exists, we do not reroute. We use the existing page. If the file doesn’t exist, we try to route. Our first step in the controller part of the website.

1
2
3
4
# Page redirect - if page doesn't exist, output URL as querystring
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?route=$1 [L]

Second, the index.php file explained. This is our second hit as we’re attempting to render our page, whatever the page may be.

1
2
3
4
// Basic session start
session_start();
// load in your database connections and other common functions
require_once( $_SERVER['DOCUMENT_ROOT'].'/helpers/functions.php' );

The configurations in the index.php file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Currently our configurations are set in an array. We can easily move this to another file.
$_config = array();

$_config['site_domain'] = 'http://'.$_SERVER['SERVER_NAME'];
$_config['section'] = '';
$_config['showadminheadercontent'] = true;
// we use the page config variable to determine the page we're requesting.
// If it's blank, we're obviously grabbing the index page.
$_config['page'] = 'index';
// Same concept as above, a pagelet is a sort of a modular page.
// If the pagelet is not requested in the URL, we set it as "main" for every page.
// We use this in order to grab different pages or views, or to determine what
//   files we need to request.
$_config['pagelet'] = 'main';
...

The router in the index.php file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// This is where we get the router as passed in by our .htaccess file.
if (isset($_GET['route'])) {
    // a simple explode to get all of our values from the URL.
    // The format of the incoming URL will always be /part1/part2/part3/etc...
    $route = explode("/",$_GET['route']);

    // we check to see if our route contains anything in the first part.
    if (isset($route[0])) {
        // if we have an admin section, this is where we would check for that.
        if ($route[0] == 'admin') {
            // This means that we're in the admin section. So, we can set this in our configuration.
            $_config['section'] = '/admin';
        } else {
            $_config['section'] = '/';
        }
    }
}

You can continue with the rest of the routing the same way. $route[1] can be your page call, $route[2] can be an action call, and $route[3] and beyond can be variable values passed along.

You can also set your $_config[‘page’] as $route[0] or $route[1] depending on if you’re in the admin section or not. We do this in order to store the value in ONE variable instead of the $route[0] or $route[1] variable, and constantly use a conditional to determine the page we’re on.

Next step in the index.php file is the models. We want to load the models after we’ve gathered all information required. If you want to add a “language” setting to the site, do it before the models.

1
2
3
4
5
6
7
8
9
10
// define your model name here.
// the folder structure for models is: /models/&lt;section&gt;/&lt;page&gt;_model.php
$model_name = "/models".$_config['section'].'/'.$_config['page']."_model.php";
if (is_file($_SERVER['DOCUMENT_ROOT'].$model_name)) {
    $_SESSION['error'] = '';
    require_once($_SERVER['DOCUMENT_ROOT'].$model_name);
} else {
    $_SESSION['error'] = "Model $model_name not found.&lt;br&gt;";
    echo '&lt;div style="border:1px solid #f00;"&gt;'.$_SESSION['error'].'&lt;/div&gt;';
}

Our models are based on a folder structured mentioned in the code:

1
/models/
/ _model.php so if your URL looks something like this:

http://website.com/info

There will be an attempt to load the model: /model/info_model.php

If that model does not exist, an error will display.

Following the next step, it’s time to write some HTML out to the page. This is where the Doctype, html, head, body tags are send to the page for rendering.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en-US">;
    <head>
        <!--[if IE]><link rel="stylesheet" href="/css/main-ie.css" type="text/css" /><![endif]-->
        <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="/css/site_<?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/combine_css.php'); ?>.css">
        <link rel="stylesheet" type="text/css" href="/css<?php echo $_config['section']; ?>/main.css">
        <?php
       if ( function_exists ("loadMoreCss") ) {
           loadMoreCss();
       }
       ?>
    </head>
    <body>

Notice several things above. We’ve added an ie css link for those of you that need to tweak css for IE. This section is where you load your CSS ONLY, do not attempt to load any javascript. Javascript will be taken care of in the footer.

Another thing to notice was that I used a CSS combiner to combine all of my common CSS, like jQuery UI CSS, Fancybox CSS, and other standard CSS that I use on all my projects.

Also notice that loadMoreCss() function. This is in case your page will require additional CSS to be rendered, we don’t want to include it EVERY page on our site.

All of the above should be placed in the loadHeader() function. Don’t forget to global your $_config array.

The body will be explained in a different post. I will also make this tutorial available in the pages section.

Framework – Rework

I’ve been busy working out some of the kinks in the framework, and the best way is to actually put it to good use. Build a website with it.

This is my second website that I’ve started work on, with nesting of pages, subpages, etc involved. So, after putting the framework through the ultimate test (actual website development), I’ve re-written some of the features for it. Things such as pagelet model loaded from the main.php file in the page folder dynamically.

Tomorrow I will re-work the front end because it took me two days to rewrite the backend of the website.

I can’t say too much about the project that’s based on the CMS, but once it’s launched, you’ll know about it.

Not another CMS…

I’m working on building a new CMS based on a custom framework. Currently, I don’t have a name for it. This is not a framework for the inexperienced. This is definitely a framework that requires some basic programming skills.

The three CMS packages are not for the non-programmers. Let’s face it, when did mom & pop ever feel comfortable editing their own blog, or build their own website? The reality of web design is that, there will always be a web designer who either sets up the website, or sets it up and maintains it.

This is where my framework/CMS comes in.

Stay tuned for more information, as currently I’m working on the first CMS package to be released later this month. This is a simple site CMS, meaning that it’s not for a blog site, it’s not for an e-commerce solution, it’s for simple business card type websites.

Why not just use the other simple CMS solutions out there you say? As  mentioned, this is a CMS for web designers to handle, not mom & pop. It’s definitely not as bloated as some CMS solutions out there, but it’s really simple to us.

It uses jQuery as its main javascript library, and fancybox comes standard.