PHP Frameworks Suck

It’s kind of funny. After trying to understand Zend 2, I decided that I was happier with Core PHP. I noticed that anyone can pick up any framework and learn it in a few days, or even a few weeks, but to master it, you really need to spend a lot of time with it. I’ve spent 11+ years with PHP at the time of this writing. I know PHP.

Why have any framework? For most do it yourself type projects, just build a website from the ground up. You already have 4 great layers (Apache or server, MySQL or Database, PHP or backend language, and HTML, CSS, JS all in one). This looks like a LAMP stack to me. Why do I like keeping it this simple? Well, you don’t “need” anything else. Really. This is all you need to build anything. And I do mean, ANYTHING! You name your project, and i can build it.

My only caveat is jQuery. I’ve gotten used to it over the years, and in a way I wish I could go back to plain JS. I mean, for the most part, I still use JS, I just use jQuery for selectors / DOM manipulation, events, and the ever so simple to use ajax function. The main reason I use jQuery is because, otherwise, I would just write my own functions to do all these things. jQuery just makes sense to use.

My next task is to convert all my jQuery into JS at some point. Why? Because that’s what the browsers understand. The browsers don’t understand jQuery, or angular, or LESS or SASS on their own. They need pre-processors and libraries to convert all that.

This brings me to my other point. The backend should be no different. PHP is what is already installed on the server. Running PHP code in your files speaks directly to the PHP installation on Apache. You don’t need additional overhead to make things work better. Write PHP, done. You can structure your PHP in logical functions to make it work for you, such as getMeSomeData(), or renderThisHtmlBlock(). But that’s it. At its core, PHP is a great and most opened and powerful framework of all. Why add so many layers of abstraction on top of it?

My next good practice is to write MySQL directly into my php code. Why not? That’s the fastest processing you’re ever going to get without involving overhead. Use propell? Why? Just so you can stack php functions that eventually build out what you meant to say with MySQL anyway? Again, more layers of abstraction? What’s the point? Because it doesn’t “LOOK” like SQL? Is that really a valid excuse? Learn some damn MySQL like a good programmer, and remove all those PHP overhead functions to keep your site optimal.

It’s not what you use, it’s how you use it. Developers have become so lazy over the years, and no one cares about code itself. They treat it like they’re bored of it and just need to add layers of complexity.

The only thing that matters is how the client side performs. All of my projects’ pages load faster than 2 seconds, out of which most load under 1 second. In the end, that’s what matters. And, the turnaround time for most of my development is minutes, not days like most projects dependent on builds.

And I simply don’t want to discuss things like memcached, composer, ruby (for SASS), or any other dependency that’s simply not necessary. Are your websites fast? Then, that’s what matters. I worked at this one company where they would be concerned with micro optimizations such as to use array brackets instead of array_push function. At the same time, they were using propel that would run through dozens of php functions to get data, and their pages were loading in over 4 seconds, with unoptimized images, and over a hundred http requests. I just don’t understand this sort of mentality. These things should matter no matter if you are running an SEO site, or a private LAN intranet. Users will complain when your site loads in over 2 seconds. That’s a rule.

I’ve built many systems over and over and over only to come to the same conclusion. Simplicity just works better. Ask Steve Jobs.

The reason Angular JS will fail

I’m all about new technology, but just like Steve Jobs had put it, it has to be intuitive. It has to feel comfortable, and easy to learn. This is reference to another one of my posts done here: Angular JS Kinda Sucks. The main reason Angular JS will fail is because it’s difficult. Honestly, who likes to make their lives more difficult? Not this guy. That’s not to say I’m looking for the easy way out. I believe in hard work paying off, but to make things difficult just for the sake of saying that I did something difficult that I could have done with ease, other ways? That’s just ridiculous. Yes, I can take a boat across the English channel, but why not make it harder and swim it? Other than getting into the book of world records, there really is no practical reason to do so.

Which brings me to the pattern of ever failing technologies. Remember Moo Tools? Prototype? I do too, and sadly, I use NONE of them in any of my projects. jQuery has evolved with the times. It has gotten better and better, and even with its 2.0 release, revolutionized. All while keeping its key ingredient of keeping itself simple to use and logically understandable. Any one of us who struggled with JS before jQuery came along created our own JS libraries to handle mundane tasks of JS. Class lookups, selecting elements, animation, AJAX, etc. We all wondered if there was an easier way to do repetitive work like that. jQuery came along and helped us out in that department.

Prototype and moo tools tried to be innovative, but they just made things harder. Not only were they not intuitive to use, but referring to the documentation was even worse. Would take hours what jQuery could accomplish in mere minutes.

Don’t look at how many companies use those other tools right now. Wait for it and see how many companies will use those same tools in the future. 5 years, 10 years… jQuery has stood the test of time. And the reason they keep winning is because they cater to the developer, the people who are using the tool the most, and making their lives easier to deal with. It’s a complement to code, not a spaghetti nightmare filled with complexities and high learning curves.

I remember the first time I built a web page using jQuery. It was easy. It was instinctive. It was amazing. It made want to use more of it. AngularJS unfortunately, did not have that same effect on me.

In the end, I guess it’s to each their own, but too many times I’ve come across reviews that are not so pleasant to read about Angular JS. Even doing a google search on “jQuery sucks” vs “AngularJS sucks” shows that there are more results for the latter, and AngularJS has only been around for a few years, while jQuery, almost a couple of decades. You’d think that there would be more results for jQuery since it’s been around for longer, and that AngularJS has been harbored by Google.

What are your thoughts?

Angular JS Kinda Sucks

Ok, so I ran across this angular js framework and looked it over, tried to duplicate some functionality that I already had existing with jQuery, and was not impressed.

First of all, I can do anything in jQuery, and have full control. Full control of the selectors, HTML, the DOM. I like that. I like knowing what I’m doing and what’s happening in my application. Somehow, angular fails to let me know what’s happening behind closed doors, unless I go dig into the code itself. Hm. Never had to do that with jQuery.

+ jQuery

The documentation is just plain horrible. Basically, it comes down to how basics work, not how you can and should build an application, even though they stress that you must first architect your application before you build it. Architect it how? Are there examples? Some nice examples would be of projects that are relevant to the outside world. Data manipulation? Dynamic AJAX driven application? It just seems like a lot of hype because it’s the “cool” thing to do and everyone is doing it. Well, not everyone. About 0.1% of sites out there use Angular, while well over 55% of websites use jQuery. Most of the documentation is just hard to understand without explaining the parts of the application or explaining the magic behind the app, or even explaining why I’m naming certain things the way I name them. Anyway, just confusing.

+ jQuery

Which brings me to my final reason for not liking it. Intuitiveness. It’s not intuitive at all! If you know JS and jQuery, everything is build so you can just figure things out. .show(), .hide(), $.ajax({stuff}), $(‘whatever selector you want full control of here’).doThings(). It’s easy to read, just like OOP. In angular it feels like you’re looking at fog. ng-this, ng-that, and now you have to assume that somehow everything is aware of everything else on the page. WTF?

+ jQuery

Speed of development? Hardly. We had some experience with it at work where some front-end code was handed down to be integrated by back-end guys, and… well… everything broke. Why? The back-end guy knew only jQuery. Now, he has to spend additional time and resources to learn angular, and the learning curve is STEEP!!!! And once he learns it, maybe someone will come up with another stupid framework that will do exactly the same thing jQuery does, only more abstract. Can we get practical with our development, stop being such lazy-ass programmers, learn to code properly, and stop complaining about how working on something feels like work? Beware of lazy programming and short cuts to faster deployment schemes. Sounds a lot like get rich quick schemes. How well have those worked out so far? Is everyone rich yet?

+ jQuery

Just not for me. Might be for you, but for me, I stand by the saying, “If it ain’t broken, don’t fix it!” And jQuery is definitely not broken. It’s by far the most favorable, intuitive, powerful “framework”/library to date. It’s not a hula hoop. It’s a cellphone.

Updated on Feb 27th, 2014:
After attempting to look through documentation and examples on stackoverflow, I’ve come to the conclusion that I’m much happier with jQuery, for the simple reason that I know how to use it and it does everything I’ve ever wanted, because it’s a tool for short-cutting a lot of mundane tasks that JS threw at us. .each() loops, .ajax calls, class selectors, very easy to understand and build on top of. After looking at many examples of angular implementation, I’ve noticed a pattern of jQuery being used on top of angular. Obviously to take care of the many things that angular can’t. It seems to me that performance wise it wouldn’t be smart to use angular, simply because it would be additional bulk on top of your programming. It doesn’t complement JS, it complicates it by changing the rules, and way of thinking. jQuery respects JS and complements it greatly. So…

+ jQuery

If anyone has the solution to how they would take care of the example I’ve created using jQuery with angularjs here, I would love to read it.

Finally, The vBox Plugin!

Ever wanted a nice plugin that you could just insert, and run with it? No major reconfigurations, no extra images, nothing of the sort.

Bad news first!

Here are some of the cons:
- Modern Browser Support only.
- IE 9+
- Chrome 4+ (all)
- FF 3.5+
- Safari 5.1+
- Safari Mobile 5.0+
- Android 4.0+
- Chrome aor FF for Android (all)
- Dependent on jQuery.

And the good news!

Here are some of the pros:
- Resizeable with window if contents are larger than window.
- Multiple levels, stackable.
- Based on jQuery, easy to implement and use.
- Always stays in the center.
- SUPER light!

Take it, make it, minimize it, do whatever to it. Feedback would be appreciated.

vbox-0.1.2
Updated from 0.1.1: Added a resize on any element within that has the class resizable to fit the pop up which fits the window itself.

vbox-1.0.0
Updated from 0.1.2: Added compatibility for other browsers. Added custom fade time.

Usage:

1
$.fn.vbox('open',{content:'<p>My internal HTML text.</p>'});

If you want to read it without opening the file, here you go:

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
37
38
39
40
41
42
43
(function($){
    var g_vboxlevel = 0;
    $(document).on('click','.vbox-close, .fuzz',function(e) {
        e.stopPropagation();
        $.fn.vbox('close');
    }).on('click','.vbox-content',function(e){
        e.stopPropagation();
    });
    $(window).on('resize',function(){
        $.fn.vbox('resize');
    });
    $.fn.vbox = function (action,options) {
        var settings = $.extend({
            content: 'sample',
            speed: 100
        },options);
       
        var win = $(window);
        var winH = win.height();
        var winW = win.width();
       
        if (action == 'open') {
            g_vboxlevel++;
            $('body').append('<div class="fuzz" id="vbox_'+g_vboxlevel+'"><div class="vbox"><div class="vbox-content"><div class="inner-content">'+settings.content+'<a data-id="'+g_vboxlevel+'" href="#" class="vbox-close">×</a></div></div></div></div>');
            $thisbox = $(document).find('#vbox_'+g_vboxlevel);
            $thisbox.animate({opacity:1},settings.speed,function(){
                $.fn.vbox('resize');
            });
        };
        if (action == 'close') {
            $(document).find('#vbox_'+g_vboxlevel).animate({opacity:0},settings.speed,function() {
                $(this).remove();
            });
            g_vboxlevel--;
        };
        if (action == 'resize') {
            $thisbox = $(document).find('#vbox_'+g_vboxlevel);
            $thisbox.find('.inner-content, .resizable').css({'max-width':(winW - 100) + 'px'});
            $thisbox.find('.inner-content, .resizable').css({'max-height':(winH - 100) + 'px'});
        }
       
    }
}(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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
.fuzz {
    position: fixed;
    background: rgba(0,0,0,0.5);
    width: 100%;
    height: 100%;
    display: table;
    text-align: center;
    vertical-align: middle;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    opacity: 0;
}
.fuzz .vbox {
    display: table-cell;
    vertical-align: middle;
}

.fuzz .vbox-content {
    box-shadow: 0 9px 39px #333;
    display: inline-block;
    padding: 20px;
    background: #fff;
    position: relative;
}
.fuzz .inner-content {
    overflow: auto;
    border: 1px solid #ccc;
    padding: 20px;
}
.fuzz .vbox-close{
    position: absolute;
    font-size: 28px;
    text-decoration: none;
    top: -12px;
    right: -12px;
    border: 3px solid #fff;
    box-shadow: 0 0 10px #000;
    border-radius: 16px;
    height: 26px;
    line-height: 22px;
    background: #000;
    color: #fff;
    width: 26px;
    font-weight: bold;
}

Update:

I’ve managed to make some tweaks with the help from some feedback and the vBox plugin is finally ready for release. Enjoy!

Who’s JSON?

J. S. O. N. Actually

Not sure where I’m going with this, but here we go. I like JSON (JavaScript Object Notation). What’s that, you say? You mean, who’s that? Oh, wait. No, it’s ‘what’s that’.

What I’d like to start with is something experimental. Let’s focus on the idea that there is a back-end, and a front-end to any development, especially web development, and especially web application development. What if both sides could simply just communicate with itself via JSON. Why JSON? Because JSON is super light weight for transferring data. What kind of data, you ask? Any kinds. Sure, we could render out code via an AJAX call as HTML, but all those little extra tags are overhead. JSON keeps it simple with only one or two additional characters per variable or value. Let me show you what I mean.

1
var myObject = { "person" : { "fname" : "John ", "lname" : "Donson"} };

Notice what happens in the block of code above. I’ve specified an object with enough information to arrive at the conclusion that this data is related to a person, and their name is John Donson.

jQuery can easily do this JSON encoding from arrays, strings, etc. You just need to pass it the variable:

1
var myObject = $.parseJSON( '{ "person" : { "fname" : "John ", "lname" : "Donson"} }' );

Please note that I’m using double quotes inside the object itself. This is proper JSON format. Escape any single quotes with backslashes. This gives us an object that we can easily inspect in the console log of Firefox.

All right, now that we understand who JSON is, let’s have fun with him.

HTML5 Kicks in

Wouldn’t it be great if we could use HTML5 to send some data to JavaScript who can in turn send the data to the backend (PHP), who can then get some data from a database and return back some JSON code that we can use back in JS to manipulate elements in HTML5?

Wow, I mean, why even go down this road? Simple. Large amounts of data to be processed. PHP may be fast at 300 requests per second, but HTML is even faster, with 1000 requests per second. The idea is to develop for online applications. Such as, a game, or management systems.

Let’s start from the top. Here come’s < a >.

1
<a href="javascript:void(0);" class="jsonCall" data-get='{"url":"/ajax/main.php","data":{"var1":1,"var2":2}}'>Click me!</a>

Whoa, why all this? Let me break it down.

- The void call in the JS call is to make sure older browsers don’t show a white page when clicked.
- We’ve added a class because we want to identify any element with an action. Doesn’t have to be an < a > element.
- data-get is our HTML5 way of introducing data that we will need. This is our JSON data that we will send from JS through our AJAX call.

Let’s see where this takes us.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$(document).ready(function(){
    $('.jsonCall').on('click',function() {
        var queryVars = $(this).attr('data-get');
        var qJSON = $.parseJSON(queryVars);
        var qString = "internal=true";
        for (data in qJSON.data) {
            qString += "&"+data+"="+qJSON.data[data];
        }
        $.ajax({
            url: qJSON.url,
            type: 'post',
            data: qString,
            dataType: 'JSON'
        });
    });
});

This is the entire code we need to parse out our data-get attribute value and send it out for processing. Let’s put what we did into practice.

Practice Makes Improvement, Because No One is Perfect

Let’s say we want to load a list o thumbnails with descriptions and links to another page. So, let’s set up the scenario.

What we need:
- link
- thumb
- text

There’s the classic way and try to render everything out on the backend, and spew out some static html that can be placed inside our “container” whatever that container will be.

Why not make it smarter, and just send a request for the items you need. Let’s say you need 16 thumbs because that’s how many thumbs will be on the page at once. Yes, you can always change this number, but 16 is perfect for a 4×4 display of thumbs.

First, we need to understand what our content might look like. It will probably look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<ul>
    <li>
        <a href="">
            <img src="" />
            <span></span>
        </a>
    </li>
    <li>
        <a href="">
            <img src="" />
            <span></span>
        </a>
    </li>
    ...
</ul>

Ok, it will be a little more intricate than that, but here’s the reason to load your content with JSON. All of this above is simply overhead. None of our data has been loaded yet. There IS no data! So, with all this effort of rendering out, we got back a big fat nothing.

Why not templat-ize the results? It would make much more sense. Why not load the template HTML content inside our current document so we can just use it? Since it will be used anyway on the page, load it up, but keep it hidden.

1
2
3
4
5
6
7
8
<script id="content-list-item" type="text/x-jquery-tmpl">
    <li>
        <a href="[[url]]">
            <img src="[[thumb]]" />
            <span>[[text]]</span>
        </a>
    </li>
</script>

This would allow us to get the content via the jQuery.html() function, replace the values inside the double brackets, and append this element to the container.

Doesn’t make sense yet? Let’s compare the old way we used to do things. If we had a loop of items on a page, we would render everything at the php level right after we got the data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$qty = $_POST['qty'];
$retVal = array();

for ($itemCount = 0; $itemCount < $qty; $itemCount++) {
    ?>
    <li>
        <a href="http://www.motortrend.com/roadtests/oneyear/coupe/1302_2013_scion_fr_s_arrival/">
            <img src="http://i2.squidoocdn.com/resize/squidoo_images/-1/lens10584771_1271704447MARIO_thumbnail.jpg" />
            <span>2013 Scion FR-S Arrival</span>
        </a>
    </li>
    <?php
}
?>

This would be fine, if the data would remain minimal, but where are your alt tags, title tags, what if you use itemprops for SEO results. All that is additional overhead.

Our template contains almost the same amount data returned as JSON. The reason being is that we’re not returning

1
<a href="

as data, but we’re most likely returning

1
{"

instead. Less code already.

But, you say, the difference is not that great. We went from 236 bytes to 258 bytes. It’s not a huge difference. It’s about 9%. I’m not impressed.

Ok, what if you do add those additional items, like title, alt, propitem, etc… And what if you have additional wrappers and other overhead HTML that repeats? Your template only includes this once. The rendered version of your code returns this 16 fold. Let’s see the difference between.

235 to 305!!! How’s 30% increase in your data for a significant enough number?

In Conclusion

So, when comparing the two methods, you notice that our template has been increased by a few bytes.

1
2
3
4
5
6
7
8
<script id="content-list-item" type="text/x-jquery-tmpl">
    <li itemprop="stuff">
        <a href="[[url]]" itemprop="url" title="[[text]]">
            <img src="[[thumb]]" itemprop="image" title="[[text]]" alt="[[text]]" />
            <span>[[text]]</span>
        </a>
    </li>
</script>

Our JS has not increased since we’re just reusing the same references for the alt, title, etc tags.

While the oldmain.php rendering file has increased a bit more than the template file, this repeats several times, significantly increasing the size of data transferred back to the client.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$qty = $_POST['qty'];
$retVal = array();

for ($itemCount = 0; $itemCount < $qty; $itemCount++) {
    ?>
    <li itemprop="stuff">
        <a href="http://www.motortrend.com/roadtests/oneyear/coupe/1302_2013_scion_fr_s_arrival/" itemprop="url" title="2013 Scion FR-S Arrival">
            <img src="http://i2.squidoocdn.com/resize/squidoo_images/-1/lens10584771_1271704447MARIO_thumbnail.jpg" itemprop="image" title="2013 Scion FR-S Arrival" alt="2013 Scion FR-S Arrival" />
            <span>2013 Scion FR-S Arrival</span>
        </a>
    </li>
    <?php
}
?>

Another benefit is that the template can be changed as an individual file. So, if designs change, you never have to bother the back-end developers, unless new data is necessary for the items retrieved, but that’s a data issue, not a design issue.

Updates to the other files:

The call is being made from here

1
2
3
<a href="javascript:void(0);" class="jsonCall" data-template='#content-list-item' data-container='#my-container' data-qty='16' data-action='getmario'>Click Me!</a>

<div id="my-container"></div>

The JavaScript updated file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    $('.jsonCall').on('click',function() {
        var template = $(this).attr('data-template');
        var container = $(this).attr('data-container');
        var action = $(this).attr('data-action');
        var qty = $(this).attr('data-qty');
       
        $.ajax({
            url: '/ajax/main.php',
            type: 'post',
            data: 'qty='+qty+'&action='+action,
            dataType: 'JSON',
            success: function(data) {
                $(container).html('');
                var templateCode = $(template).html();
                for (var itemCount = 0; itemCount < qty; itemCount++) {
                    templateCode = templateCode.replace(/\[\[url\]\]/gi, data[itemCount].url);
                    templateCode = templateCode.replace(/\[\[thumb\]\]/gi, data[itemCount].thumb);
                    templateCode = templateCode.replace(/\[\[text\]\]/gi, data[itemCount].text);
                    $(container).append(templateCode);
                }
            }
        });
    });

The ajax called JSON returning php file

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
<?php
// a sort of a controller to get the right function to run
if (isset($_REQUEST['action'])) {
    switch ($_REQUEST['action']) {
        case 'getmario':
            getMario();
            break;
    }
}

function getMario() {
    // normally would make a database connection to populate the data,
    // but that's not what we're testing here.
    // We only made one connection per call anyway.
    $qty = $_POST['qty'];
    $retVal = array();

    for ($itemCount = 0; $itemCount < $qty; $itemCount++) {
        array_push ($retVal, array(
            'url' => 'http://www.motortrend.com/roadtests/oneyear/coupe/1302_2013_scion_fr_s_arrival/',
            'thumb' => 'http://i2.squidoocdn.com/resize/squidoo_images/-1/lens10584771_1271704447MARIO_thumbnail.jpg',
            'text' => '2013 Scion FR-S Arrival'
        ));
    }
    $retValJSON = json_encode($retVal);
    echo $retValJSON;
}

?>

Just to show once again that the more complex your html will be, the more data you are returning the old way, whereas the new way, you are barely adding anything at all to the data coming back. In the long run, you will benefit significantly from the template way of doing things.

Changed the oldway file:

1
2
3
4
5
6
7
8
// from
...
<li itemprop="stuff">
...
// to
...
<li itemprop="stuff" id="item_<?php echo $itemCount; ?>">
...

Changed the template file:

1
2
3
4
5
6
7
8
9
10
11
12
// from
...
<li itemprop="stuff">
...
// to
...
<li itemprop="stuff" id="item_[[id]]">
...
// and added this line to our array of data
...
'id' => $itemCount,
...

Minor changes, HUGE difference. The new results are in, and the new way has gone up to 268 bytes, while the old ways have gone up to 353 bytes. Now we’re at 31.7% increase which goes to show you that we went from just under 30% difference to 31.7% (almost a 2% increase in bandwidth, just from a single change). This might be nothing when considering the small size of data, but for multi million user websites this number can be real significant. And it separates your code better.

Yes, you will use up more space initially when loading the templates. About 115 bytes more, but in the long run, there are greater benefits.