Are PHP Frameworks All Hype?

The short answer is, yes.

Let’s explore why that is.

Who in their right mind would try to sell their framework idea by saying, “It’s slower than straight php”, or “it lacks form customization”? I’m pretty sure no one would. This article is based solely on my own personal experience of dealing with web development for over 13 years.

I want to start out by saying that I’ve tried many PHP frameworks. I’ve tried Cake, Magento (a CMS loosely based on Zend philosophy), Symfony2, Zend2, Yii, Codeigniter, Light VC, Laravel, and many other in my own personal time). One thing to note is the amount of frameworks that exist out there just for PHP alone. Why so many? If any one of them were as good as PHP itself, why hasn’t it become the standard? The reason may shock you… or not. PHP frameworks suck! Even Rasmus Leerdorf himself (the creator of PHP) had said it.

Web development and web application development is not the same as any other type of programming. It’s development that creates short lived web pages (applications) and rapid AJAX calls in order to provide the end user with some sort of interaction and/or data management. These little pages, together create the illusion of being “logged in” an application. Applications keep massive amounts of data alive until that application is shut off. Think of the OS that you’re on right now. TONS of things happening in RAM while you’re listening to your favorite music and reading this post. On this particular website, the page has already loaded. Nothing much else is happening. The web app finished rendering a long time ago and is now in a sort of an “off” state. I just want to make sure we understand the differences between web app development and any other type of application development where the data stays alive for the entire duration of the application.

Yes, there are exceptions, such as sockets, but for the most part, most websites render out, and boom, done! The server on the other hand may keep a session alive. If not, your authentication is probably handled by cookies, or RESTful api keys and secrets. Anyway.

Trying to introduce a concept of MVC, previously only used in single language environments (i.e. Java), to a multi language environment (Apache, PHP, MySQL, HTML, CSS, JS, etc) is plain ridiculous. I understand the idea behind separating code, but for a website, it’s ludicrous to think that you can do all of data collection through PHP, or all of the JS calls from PHP, or even CSS rendering from PHP. Websites are a special type of applications that can, and should handle multiple types of languages in order to provide the best experience for end users, visually, and functionally. Imagine if we could only code websites in PHP alone. What a mess that would be.

The simple truth, and this may hurt anyone out there, is that with all of these different frameworks, not one has stood the test of time over a two year period. Everytime PHP gets updated, your frameworks becomes useless. All the bells and whistles just became obsolete. And forget about v2.0 of the framework since nothing is backwards compatible. It’s a complete nightmare.

I always hear the argument about how noobs pick up a framework faster. Faster than what? PHP? Don’t they have to learn PHP first? And if they know PHP, why learn another layer on top? What if you had to hire new developers? You’d have to teach them the framework, and look back at how long it took you to become an expert in the framework, not learn it, but become an expert. Why an expert? Because you made a lot of mistakes while you were learning it, and you can’t afford that with noobs.

Build your PHP code to make sense, and the same goes for code as it does for UI. If it takes more than 3 clicks to get somewhere, it’s probably too complicated. And you know what? No one is going to want to work on that project. Sure, you can hire a framework or CMS specialist and pay them twice as much… but why do all that when you can get two developers for that same price with a simpler system in place? Response / request. That’s it. That’s what the browser understands. Built it that way, and stop calling everything an application as if you were building something in JAVA. Focus on architecture, not frameworks.

The shortest path is one best known. And surprisingly, most php developers know php.

Are flowcharts making a comeback?

If they’re not, they should be.

Once too many times I’ve seen development go awry. It’s insane to think that you can build a full application by code alone. Since the days of “modern” programming practices, such as OOP and frameworks, there has been this misconception of the code documenting itself. What a misnomer!

Proper software development is done in three main stages. 33% of the time should be spent on documentation. 33% on development, and the last 33% on QA. The leftover 1% can be spent on whatever else you’d like. But seriously speaking, this is the way software development has proven to be effective and efficient. But wait, you might say, what about projects that change their requirements from day to day? Think about what was just said. We’re going to build a product that will change from day to day. Might as well build a house out of LEGOs. It will not be a well design product. Imagine if any other industry would do that wing-it approach. Cars that break down once you drive them off the lot because they haven’t been tested properly, even though their internal tests say nothing’s wrong. Imagine having to tweak the car every day or week because new bugs have been discovered. If you want to be serious about the product, know and understand what you’re building. Commit to what you’re building, and build it. Just like building houses. There’s a blueprint for a reason. You draw it, commit to it, then you build based on that commitment. Once you chose to not have a basement, it will be super expensive, and insane to try to add a basement to your house. And all the while the blueprints are being developed, guess what. There’s no house to demo to the owners. There are prototypes and models and artist renderings. Modern day software can make a 3D replica of it on your PC, but the house itself is not actually built. Why is software any different? Why are we not showing software the same level of respect?

When you commit to it, that’s where the fist 33% comes in handy. This is something you’re going to build, not just “wing it”. Yes, I’ve actually heard the phrase to “wing it” in planning meetings, by the director of IT. Flow charts, flow diagrams, user flow design, interactive wireframes, mocks all should be done at this point. The product being built has to be understood. NO CODING! I’ve heard one too many times (but we have to show something). Show the flowcharts, the prototype if you built one, the wireframes, the mocks, everything else. Just don’t code it. There could be the small chance of the project changing direction, and instead of it being something easily built in JAVA, it could be something that could be best built as a web-app.

Another 33% of the time should be spent on actual development. Does this mean that there won’t be questions regarding processes? Absolutely not. There should be questions. There should always be questions, but the amount of misunderstanding is significantly lower. It’s no longer about “should we have a basement or not”, but more like, what paint would fit better with this room because of the light coming in from the Sun. The changes here are minimal, with very little impact. By this point you have to FULLY understand the business logic of the application. In the case of games, you have to understand the user flow, the storyline, etc. If you don’t know what comes into the black box, and you don’t know what you’re supposed to be out of the black box, don’t code! When you do begin coding, you should have all of your flowcharts not only fully complete, but also approved by everyone on your team. But, you say, why would a designer need to look at flowcharts? Well, I say, if there’s a logical process happening, and the “No” response generates a process such as “Display email format error to the end user”, the designer needs to know that he needs to make a mock for that scenario. The copy people (text assets) need to clarify the exact text that goes in that error. The UI person needs to understand if this error will be a generic pop up, an inline element below the input field, or a general error box below the form. So, for something that a “winger” might consider a waste, I just showed you exactly why we need flowcharts discussed by all team members from design, to UI, to product, to copy, and then the developer. And it’s for something as simple as “display error”. Think about the mess of having to re-code your code base because you placed a typical alert box, and then someone comes by and tells you that it should be an inline red text appearing below the input box.

This is why the 33/33/33 rule works extremely well and effective. I have been on too many projects where we spend 150% of the time developing and re-developing, and the rest of your life QAing. No clear scope, no defined requirements, no DOD (definition of done), nothing. It’s ridiculous to think you’re accomplishing anything of good quality this way. For me, personally, I refuse to write code before I understand the product for the same reason a mason refuses to lay down the first brick… carpenter refuses to hammer their first nail… or concrete mixer refuses to pour their first cistern before they get a blueprint. Whatever it is they’re building, it could be a wooden framed house, a military bunker, or a castle. Imagine the waste, or crappy construction if they built their masterpieces like we write code today. Major FAIL!

Let’s treat every project as if it was our own, and treat it with the respect it deserves.

And please, code responsibly.

CodeIgniter, The one semi decent framework… is done

I’ve been playing around with CodeIgniter, and although I’m not a huge fan of 3rd party PHP frameworks, I would have to say that CodeIgniter is probably the easiest out of the box solution. Of course, I still have to build everything that I need for it. It’s not like it comes with an image cropper, or a customized user profile area already built, but for its MVC structure, it’s pretty decent.

I’ve recently started to dabble in its query-ing capabilities. Although I like writing sql queries out by hand, and yes, insert them into my PHP code (model files under my models folders), what it has is a decent enough, and simple way to do get and set some data. Not bad… Until you come up to a query like this:

1
SELECT id, ( 3959 * acos ( cos ( radians(78.3232) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(65.3234) ) + sin ( radians(78.3232) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 30 ORDER BY distance LIMIT 0 , 20;

At which point… why even bother to use an ORM, or DAO? You’re just going to mix up your code anyway… Stop trying to write everything in PHP. MySQL is powerful as is without abstract layers.

Anyway, that’s one point. The other is all of the session and cookie handing.

Why load an entire new class, object, etc like $this->load->library(‘session’); when all you really need is $_SESSION. Done! All for the purpose of writing saving some additional info that you rarely use, or can gather any other way? I suppose it’s a shortcut that needs to be learned, but PHP already does that in its way.

The best feature, which it took a little convincing, was its MVC structure. Although I like to develop modularly (MVC structure should be kept in modules, not in the entire site), I was ok with its structure, considering that I can build folders for all of my “modules” but then I would have the same module folder in three different places.

The routing for it was something that was all right. It didn’t wow me. Basically, we took htaccess rewrite conditions and converted them into an array… Sigh… 6 of a kind, half a dozen. htaccess is faster though if you want to talk performance.

So in finale, it was probably the easiest to pick up and go with, considering its learning curve and its openness to be more like PHP.

Toggle Functionality for Clean PHP

Requirements:
* jQuery
* Font Awesome
* AJAX capabilities
* .hidden = display: none;

So, I decided that just controlling the front end via the back end wasn’t enough. I debated for a long time and was reluctant to add new functionality to the ajax controller… then I realized that I’m using a lot more of this functionality, so, I caved in.

This complements the ajax functionality by adding a toggle feature for either items that toggle out (2 state on/off), or items that toggle other elements on or off; still 2 state.

The first thing I did was to add some classes to the elements that will perform the toggling. I added a wrapper around two elements (the togglers) and proceeded to play around with them.

1
2
3
4
<span class="trigger-wrapper" data-trigger="toggle">
    <a href="" class="tmbtn trigger hidden" data-action="test_toggle"><i class="fa fa-toggle-on"></i> Active</a>
    <a href="" class="tmbtn trigger" data-action="test_toggle"><i class="fa fa-toggle-off"></i> Inactive</a>
</span>

The trigger-wrapper class was added to wrap everything in one molecule.

I added the data-trigger attribute to the wrapper because this is what will determine what toggle type to perform… Is it a straight toggle of two items, show / hide an element, or both?

The trigger classes are what determines what triggers the toggle. These trigger elements will swap out their hidden classes. That’s how they toggle.

Here’s two more HTML examples of the content pieces:

1
2
3
4
5
6
<div class="trigger-wrapper reset" data-trigger="dropdown">
    <a href="" class="tmbtn trigger" data-action="test_toggle"><i class="fa fa-ellipsis-h"></i></a>
    <div class="target hidden init-hidden">
        [Content]
    </div>
</div>

… and…

1
2
3
4
5
6
7
<div class="trigger-wrapper reset" data-trigger="dropdown-toggle">
    <a href="" class="tmbtn trigger hidden init-hidden" data-action="test_toggle"><i class="fa fa-chevron-up"></i> Show Less </a>
    <a href="" class="tmbtn trigger" data-action="test_toggle"><i class="fa fa-chevron-down"></i> Show More </a>
    <div class="target hidden init-hidden">
        [Content]
    </div>
</div>

Notice how these last two items had the “init-hidden” class added, and the togglable content has “target” on it.

Now, for the JavaScript (jQuery) that drives the whole thing… (Assuming that .hidden already exists in your CSS as display: none).

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
...
var _toggle_type = '';
...
var $parent = $this.parent();
...
if (typeof($parent.attr('data-trigger')) !== 'undefined') {_toggle_type = $parent.attr('data-trigger');}
...
// In the ajax call of the JavaScript file (data is what comes back in the success function) ...
data._toggle_type = _toggle_type;
data.$parent = $parent;
postAjax(data);
...
// And of course, the switch case for the different toggles...
switch (data._toggle_type) {
    case "toggle":
        data.$parent.find('.trigger').toggleClass('hidden');
        break;
    case "dropdown":
        data.$parent.find('.target').toggleClass('hidden');
        break;
    case "dropdown-toggle":
        data.$parent.find('.trigger').toggleClass('hidden');
        data.$parent.find('.target').toggleClass('hidden');
        break;
}
...

So now, we have a lot of the functionality to handle our togglability.

This completes our addition to the Clean PHP code that I’ve been working on here: https://github.com/gbutiri/cleanphp

OOP PHP Sucks!

Update: Before you bash my head in, let me re-phrase the title… ehem… Today’s misuse of OOP sucks as much as misuse of procedural style.

After considering how the web has evolved, I’ve noticed that is not what you use to code, but how you code it that matters more. Yes, what you use still matters, but how you do it matters more. After trying to work on a project using Zend2, I gave up on it when I noticed the ridiculousness of just rendering a page with some dynamic data on it. Autoloading unnecessary libraries, adding layers of abstraction from propel which really all it does is use unnecessary clock cycles to do the same thing that writing your SQL inside a string, building objects that use something like 5% of its functions, “ingest” template files to create some sort of rendering, adding smarty templatizing on top of it that needs to convert to php tags anyway, and finally, the end result.

For real? We NEED to do all that to just render some dynamic page? Wow! We have come a long way in abstracting the simplest solutions into difficult to understand spaghetti code. I’ll explain what I mean by all this.

Let’s look at what actually happens when a web page gets rendered for end users… after all, that’s typically the medium that end users get to interact with in order to have productive or entertaining lives.

It’s a long trip. Hope you brought a book along for the ride.

– Request gets sent to a server via URL inputted by end user typically via the address bar.
– That url gets to travel to DNS servers that send the request to servers identified by IP addresses.
– The server is hit, the server then access its first landing point (htaccess and folder structures) and makes a smart decision in order to try to build some sort of a response to send back.
– At this point, the server will either send you back a message about how it can’t find a file requested, or continue to try to render something to send back.
– Let’s say some default index.html was found without complicating things too much. And let’s say that this file contains basic html, and hopefully somewhat valid html code that gets served to be sent back as data packets back to the original requester.
– The html code comes back to the browser, gets interpreted by the browser, and the browser does its thing to render out the HTML, style with some css code, and run its internal JS engine to see if it has something to do on the client side.

This is where things can get complicated, but why? We don’t have to complicate things. Let’s keep in mind that the final response is simply a long line of characters. There’s absolutely nothing “object oriented” about it. The browser simply takes what it receives and tries to do its job. It’s that simple.

Yes, some JS gets interpreted as objects by the JS engine within the browser, but that’s not for this discussion. Let’s focus on why PHP shouldn’t be OOP.

Back to the server… Here’s what the browser wants:

< html code >
< script code >
< style code >
< html code >
< html code >
< more html code >
< maybe even more script code >

Done. The browser interprets what it gets… or tries to… and renders stuff on the screen. The browser is your application layer.

I cringe every time I hear web developers saying that they’re building an application… You’re nor building squat. Your job is to create browser readable code. That’s it. Just because you’ve overcomplicated your code so much that only you can understand it half the time does not make you an application developer. Creating a browser… now that’s application development. Until that point, you’re just creating a string of characters.

So, then, webpages started to evolve to create dynamic content… So whenever you land on the root of a site, you’re really hitting a script file… something like index.php. Somewhere on the server, in a configuration file, we’ve created the logic to say that the initial point, the entry point should be index.php… we call this the Directory Index.

This file can simply contain pure HTML code just like your *.html files. But… you can do something magical on them. You can render different content. PHP (as well as VB Script used to do), can make this happen. By using the php tags () respectively, you’ve just told the php engine that there’s some code in between. So… PHP, do your thing. Look between these tags and do some work.

I keep hearing from so many new aged developers about keeping your code separated… something about code separation makes things cleaner. I couldn’t agree more… when you’re talking about keeping your styles and JS separate, that’s a great idea. When you’re talking about adding PHP tags in your pages, why are we so scared? the code is completely separated. There’s HTML and then there’s dynamic code inside that HTML that makes sense to have there. The page becomes a template. You don’t need to have template files nested 10 directories deep. The php file itself becomes the template.

I’ve actually heard this argument before… “But php tags look so ugly… so I use smarty tags”. O_O … Are you an idiot? They look ugly? So that’s why you have to add a layer of abstraction on top of it? Adding smarty is not so smarty, is it?… That layer of abstraction just made your code slower because the PHP engine has to now convert ALL of the curly brackets on the page to “ugly” php tags… You know what? If php tags are ugly, then smarty tags are stupid. If that’s the case, I’d rather be ugly than stupid.

It feels like abstraction has gotten out of hand where we now pull HTML templates inside some private function inside a file nested another 10 directories deep.

This mentality of super abstraction is what I have a big issue with when it comes to development for the web. It’s typically engineers who consider themselves super smart coming from the world of Java or C++ who somehow believe that coding on the web is the same thing as console, or application development. It’s not the same thing.

Let me explain so someone as smart as you can understand. Java development doesn’t have a browser for which you need to write a string. It doesn’t have multiple languages to handle, such as HTML, JS and CSS. It’s one code… assembly. And of course, to make it easy, there have been compilers built that can convert all of your nicely written OOP code in code that the machine understands. It gets compiled, and your code is typically living within the Java engine that you downloaded and installed (not a browser, it’s an engine with which the user never directly interacts). It stays in RAM. HTML code doesn’t stay in RAM. It gets put on a disk (browser cache). The CSS, same thing. The JS, same thing. All those pretty objects that you took all that time to build, are gone! Not in memory. Not on the disk. It’s all gone. Oh, you want to access them? Well, then we have to hit a database on a server somewhere far away from your home in order to re-build whatever you’re seeking. Get it? It’s not the same thing as app development.

If you work with PHP, you’re not building any application. You’re building code that’s to be interpreted by the PHP engine on the server in order to deliver a string of characters back to someone using a browser.

Applications, on the other hand, get installed on consoles, and PCs, and hand held devices. Upon starting the application, a whole bunch of stuff gets loaded in memory, and then the program itself uses those bits from memory. And all that stays in memory while the program is active. Only when you chose to quit the application does the application unload itself from memory. All those “object pointers” for functions and variables get cleared out.

In the end, I suppose some will never understand the difference between application and web page no matter how much you try to explain to them. Or, someone will come along claiming that they’re working on a huge website where OOP is saving their life, or some brainiac engineer claims that they don’t see how they could have built their “web app” without OOP. Obviously they’re not intelligent enough to realize that before “web oop” ALL websites were done without OOP, and they did just fine, because they built them well. It was how they coded them that mattered, not what techniques they used.

This was my rant. Thank you for listening / reading.

Update: After careful consideration, and many of your comments, I’ve come to the conclusion that it’s not OOP that I hate. I think it’s the misuse of it. Writing your models in a way that you have to load all of them for something simple… writing your SQL queries so you have to loop through database requests because you must use ORMs… instead of just writing a query that’s more complex, but increases performance 10 fold… Oh, and what’s wrong with SQL itself? It’s an awesome language to know.

I believe that it’s the way coders have been writing code that’s more of an issue for me than the actual style. PHP is not Ruby. Not everything is an object… especially when it comes to rendering things in HTML.

I’ve been using Code Igniter for my latest two projects and it’s not as painful anymore. I don’t like how it routes things as Apache is much more performant when it comes time to handle routes via Rewrite Module.

I also miss the idea of finding a page in the root (about.php) for an “/about.html” request. However… if you check your routes, it should be no problem to navigate through controllers then views (partials too). Still… looking through three or four different files to find what I’m seeking, is more work than I’d like to do… one file… off the root… about.php. Done. I suppose I can do that if I alter my htaccess file, but then… why am I using CI in the first place?

Anyway… I’ll continue to use a mix of procedural and OOP code as I’ve been doing more of lately. (Using 3rd party libraries has become a bit easier).

Once again, thanks for listening. I hope this can help other “non-believers” to understand that we need to understand our needs before we write any code.

I wonder if facebook or google uses any OOP development on the back end in their websites… er… web apps.

What Went Wrong with Web Design?

And what can we do to stop it? Standby.

First off, I’d like to start with the fact of what a website is. A website is nothing but some HTML passed in from some server. That’s it. The code that comes back from the server is static. Believe it or not, what ends up on your browser, is static HTML. The browser interprets the text that comes back from the server, and spits it out on the screen after it interprets it.

CSS and JS

If you see bells and whistles, without the page reloading, re-requesting more from the server, hover overs, text changing on the front end, that’s all controlled by some DOM manipulation. JavaScript and CSS are good at doing that. :hover and getElementById('id').innerHtml('newtext') are the secret. The good thing is that this code is available right away to use, and you can usually pipe it in additional .css and .js files loaded in the header, and/or footer.

Add Some AJAX

A great thing that JavaScript does is that is has the ability to send a request to a server, without having the browser reload the entire page, its header, rebuild its DOM, etc. That way you can really make your pages dynamic with fresh content and make it so much faster.

Here’s where it went right

The advancement of CSS2 and CSS3 has been a great release of burden on the JS engine for many of the bells and whistles. Transitions can control animation, canvas and video embedding has become a great solution for making things look pretty. jQuery, along with other JS libraries, have come along and have made the JS work easier for developers. No longer does an ajax call take 12 lines of code. I can be done in as simple as 3-4 lines. jQuery did not come along to complicate things. Let’s get this part straight.

There was MooTools, Prototype, YUI, Dojo, and many other. Why did jQuery survive? Intuitiveness to developers. It was easy to use. It was not confusing. It had decent documentation, even though it was mostly used for quick reference until you got the hang of things. But it wasn’t rocket science. With “frameworks” coming out for JavaScript these days, it just sounds like a lot of complexity for programmers who already know what they’re doing to tailor to those who have no clue how to program the proper way, and need a complex and restricting hand to hold them so they don’t color out of bounds. Yes, I’m talking about angular.js. What a bloated monster. I wonder how websites were build using just jQuery up to recently… Hm…

Here’s where it went all wrong

So, some graduating engineer students decided that a webpage was not a webpage after all, and that they needed to mess with code in order to make themselves feel better and feel more at home writing complex and overly engineered code. Then, they got lazy too. Let’s throw an out of the box framework. The boss will be impressed how quickly we can get a prototype going. And with that, the backend became constrained. No longer could you do whatever you wanted with a webpage. Now it had to follow certain paths and load every single file, even though you didn’t need to load it. This slowed down websites everywhere, because, well, autoloading does that. So what to do? Throw caching at it. So instead of realizing the problem that you’re using a framework that does not need to be used, you’re going to take what was once an exception, and make it a necessity. Besides, doesn’t caching make static files and data? How is the website dynamic anymore? Well, we’ll just delete the cache when a change is detected. So, more complexity in order to deal with the original issue of leaving the freaking webpage be a webpage.

Now you have two additional layers of maintenance to handle. Framework (which needs to be learned and experienced), and caching, which I personally know to have caused a significant number of errors throughout my development years.

But that wasn’t enough… What if we plan to change our database in the future? How are we ever going to be able to do that? Go through all of the lines of code with MySQL in them? No… why do all that work when we can throw another layer of abstraction on top? ORM Database Management. As if your website wasn’t slow as it was, let’s throw this bloated level of complexity on top of everything else that will make sure to have you spend thousands of hours re-learning how to write MySQL queries, or whatever it is that it uses. Let’s take Propel for example. Every single part of a SQL query has now become a PHP function. Talk about a waste of CPU Cycles. How often is it that you change databases? If you change your database once a year, there’s something very wrong with the architecture of your site.

Lack of documentation

Tell me you haven’t heard this a million times: “The code should comment itself”. What kind of absurd, lazy, half assed remark is that? I remember in the good ol’ days of designing a system. You should spend 1/3 of your time designing the system. 1/3 of the time implementing it, and 1/3 testing it. It seems like these days, we’d rather spend NO time on the system design, 150% of the time development, and the rest of your life QA and maintenance. There’s something very wrong with that concept. My grandfather had told me something that holds true even today. “Haste makes waste”. If you rush to get your project in front of your boss and impress him or her, you’re going to have to do a half assed job. And of course, they’re going to love it so much that instead of starting fresh to do it right, you’re just going to build on top of the prototype. And then we wonder how things got so bad. All in the name of pleasing someone else, at the risk of creating something that will break.

Take your time, and do it right.

A Custom Framework

The framework should be something that your code naturally evolves into, not something out of the box with instructions on how to do everything. How did the original creator of the framework know exactly what I was looking for? They didn’t. They made the framework to be a quick out of the box solution for themselves, and thought, hey, others might like this. And BAM, one after another, junior developers and lazy developers alike downloaded it, installed it, and now we have something that we can’t customize without breaking the barriers of the framework itself. You don’t believe me? Try setting a cookie and a session variable in Symfony2 at the start of a page. Oh, you can’t? Hm… That sucks. Well, time to whip out the good ol PHP code on its own.

How to do it right

Build an index.php file. Done. Build a header file and a footer file. Done. Build a css and js global file. Load them in your header / footer. Done. I would prefer to load JS in the header because it makes for better DOM handling within your rendering code. A rendered page would be aware of the $ jQuery object if you load your jQuery in the head.

Now that you have a one page site, make another site, and load the header and footer in that one too. Done, you have two pages. Now you can make even more pages.

Next, let’s make those URLs friendly. Modify your .htaccess file a bit and make all .html calls point to respective .php files. SEO and friendly looking, done.

So you have a very simple custom framework that doesn’t require loading hundreds of modules, models, views, helpers and God knows what other crap.

Need a global function file? Make it! Store it in a /extra folder, call it reasonably well, functions.php and start writing some functions in it. Load this file on every page before your header file. Call it a pre-header. this is before any markup is rendered. Use common sense. Store functions in here that are globally necessary. Things like database connections, input validation for emails, random password generators, number formatting (to add a 0 before a number if it’s less than 10), etc. You will need these globally, and when you need them, you don’t have to hunt for them. They are in ONE file. This file should never grow over 1000 lines of code.

If it’s too complex, it’s probably wrong

My last argument is this. NO SITE should be considered too complex to navigate, or construct. If it is, it’s probably too complex and needs to be re-thought and re-done. If your code is spaghetti, please, please, please, re-write it so anyone coming on board can easily understand what’s happening and they could trace the code easily just by starting at the index file and the htaccess file.

Growing your site to application level

Need a profile management page for your users? And admin section? A module that’s a one page app? Notice. I’ve mentioned three different things here. An admin section is not a module and it’s not a profile page to be managed. A profile page could easily be a one page form that the end user can submit. A one page app module can be a series of php, js, css files in one folder, routed through your .htaccess file. An admin section could simply be a collection of files and modules that serve the purpose to look through data on the site. Unfortunately, lately, all frameworks treat those three sections as sections of the same type. They’re all modules. That’s such prejudice. How can you say you care about your site and treat all its components the same? Not fair.

Conclusion

I just have to say that sometimes it’s good to go back to the basics and realize that even a house needs blueprints for a reason. Taken straight from the Wikipedia:

“Occam’s razor (also written as Ockham’s razor and in Latin lex parsimoniae) is a principle of parsimony, economy, or succinctness used in problem-solving devised by William of Ockham (c. 1287–1347). It states that among competing hypotheses, the one with the fewest assumptions should be selected. Other, more complicated solutions may ultimately prove correct, but—in the absence of certainty—the fewer assumptions that are made, the better.”

After all, aren’t we all essentially problem solvers?

In the end, the only thing that will matter will be the HTTP requests done by a page, and how fast your content loads in a browser. I think this is the goal that google has in mind. That’s why they try to make people develop pages that run smoother without the complicated bloated code.

On the backend, the simpler the better. Understand that it shouldn’t be rocket science. Programming should be as simple as loops and conditionals. That’s it. If it gets more complex than that, it’s wrong. If it needs to repeat, loop it. If there’s business logic, condition it (pun intended). The rest is as simple as getting data from a database (data files), and rendering them as HTML for the browser.

Respect the browser!

All PHP Frameworks Suck… Except for Mine

The thing about frameworks is that they’re built by developers to meet an out of the box solution. Sometimes, that’s a complicated piece of spaghetti code that can be used for anything, such as Zend 2, and sometimes, it can be a simple scaffolding set up in a very opened Core PHP way such as Yii, but still has the tread marks of included files and unnecessary nested functions, with an abstracted database layer.

The problem I’m having with any out of the box framework is this… Well, there are several problems.

1. Layer of abstraction for database.

I’ve heard this so many times before. What if the database changes? it’s easier to change that layer of abstraction than to go through your whole site and change the sql statements.

The problem I have with this is again, lazy developers will always make things worse for the rest of us. What you don’t realize is that by being lazy, you’re destroying your performance. Let me explain.

Typical mysqli statement:

1
2
3
4
5
6
7
8
$sql_i = "SELECT name FROM table WHERE id = ?";
$dbi = mysqli_connect(...
$stmt = $dbi->prepare($sql_i);
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->bind_result($name);

echo $name;

Ok, still a few functions to run through. Not bad though when you compare with how Yii, or Zend 2 propel queries for the same data. let me explain.

1
$query->select('table')->where('id',$id);

Yes, it looks smaller, but you’ve just added at least another object, and two more function calls. This is in addition to the back end mysql calls that happen to actually get that data. As far as micro optimization goes, this sucks. You’re not just adding two more function calls and an object; you’re adding an object and two function calls for EVERY QUERY that you run against the database.

In one of my previous work places, the lead developer was so obsessed with micro optimization that he would create arrays that would be build with brackets instead of array_push(). Obviously, the function call is more expensive when it comes to micro optimization. So, it’s ok to not be optimized when it comes to database calls only?

Then, they were wondering why their website loads at over 4 seconds. They had over 100 http request calls. No website should have over 25 calls, I don’t care how complicated your business logic. In the end, that’s what matters. Site speed is mostly determined by the amount of http requests. The problem was that with the framework they were using, it would have been nearly impossible to refactor the site to allow for concatenation of css and js files without writing it in Core PHP. What’s the point of this framework? Which brings me to my second point.

2. No flexibility for custom code

No matter how robust a framework is, it will always have constraints. There are limits to the things you can do with it. Symfony 2 for example, only allows for either sessions or cookies to be set in one call. Sessions are overwritten by cookies. So, in the end, we ended up writing Core PHP to handle both being set. Explain to me exactly what the win was there. If we’re going to avoid the framework and not use the framework’s internal functions, what’s the point of using the framework? Only to have it as a “cool” layer of abstraction? Because you think you’re cool that you know the framework?

Updates

Whenever PHP had an update, it was still PHP. New functions that would allow for more things to be done, and deprecated functions slowly making their way out. Slowly. You could still run your old code on the new PHP platform. You didn’t have to change anything, unless you wanted to optimize some of your code.

Have you ever tried upgrading from Zend to Zend 2? Symfony to Symfony 2? A freakin’ nightmare. And what’s ever worse is that with any new update to PHP, you couldn’t take advantage of this new version inside your framework. So, now you’re stuck using an older version of PHP, and a never changing framework, until the new version comes out, not having the guarantee that the new version of your framework will work with your old code.

When PHP updates, it has been usually tested by many more developers than if Yii updates. There’s a larger support group that will help you understand this new functionality. When a framework updates, the only ones that fully understand the framework are the developers of that framework. You have to pick up from the beginning and re-learn it. Sometimes this can take months. And once it’s perfected, a new version comes out. How is this progressive towards development?

PHP on its own is a framework. A much more robust, and opened framework. It will allow you to do whatever you want.

In conclusion, my theory holds true about frameworks. The best framework is the one you build from the ground up. I keep saying the same thing over and over:

“It’s not the tools you use, it’s how you use them”.

Thoughts?

Update: 8/1/2014

Happy Friday! Just to make sure we’re on the same page, I found an awesome article that pretty much states what I stated. Do not use an out of the box framework for project that require long term maintenance. Build your own with as little abstraction as possible, and only make functions out of code that absolutely repeats itself. No parameters. Read for yourself and decide. Yes, it’s a bit long of a read, but definitely worth it!

https://www.simple-talk.com/content/article.aspx?article=1274

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.

Zend 2 For Beginners Step 2

All right, guys. In response to the Zend 2 For Beginners post, I thought I’d carry on and show more on how not to be afraid of Zend 2.

If you find yourself frustrated with frameworks as I was a couple of years ago, don’t lose hope. A lot of the frameworks out there have evolved to the point where they’re very manageable. If you’re like me though, and want to do pure PHP on your own projects, no one is forcing you to do Zend. And no, using Zend doesn’t guarantee that everyone who will use it will be a better coder, or that your code will be cleaner, or faster. In fact, it takes 10 times more of the processing power to render out a zend call than a pure php call.

But, if you’re involved in working with others on Zend, I’m writing this to show you that anyone with a bit of programming knowledge can pick up Zend 2 and go with it. Simple.

Let’s start!

Here’s the structure you will need for the basic module. The bare essentials to just render out some text.

1
2
3
4
5
6
7
8
9
10
11
12
13
modules
|-- Articles
    |-- config
    |   |-- module.congif.php
    |-- src
    |   |-- Articles
    |       |-- Controller
    |           |-- IndexController.php
    |-- view
    |   |-- articles
    |       |-- index
    |           |-- index.phtml
    |-- Module.php

Don’t be scared. this is only 4 files if you look at it carefully. Yes, it’s a lot of folders, but it’s not a lot of code. Yes, clean PHP could do it in one file, but there is a lot more to worry about as far as keeping track of all of the including, etc.

So, now, let’s look at the first file: The Module.php off of the module root folder:

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
// /module/Articles/Module.php
// This line defines our namespace. The place where our module resides. Keep this the same name as our module.
namespace Articles;

// Name our class, obviously.
class Module
{
    // this is to load our configurations for routes, etc.
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }
   
    // this it to load our source files (namely, our controllers).
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
   
}

And that’s it. Basically, this file tells us to load our module configuration and autoload any controller files we may have.

The next step is to look at our config 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
30
31
32
33
34
// /module/Articles/config/module.config.php
return array(
    'router' => array(
        'routes' => array(
            // this is going to be what we call our route. It's a good idea to keep it the same name as our "link"
            'articles' => array(
                // Yes, this time, were passing in an exact match for the route. No parameters, no trailing slashes, done.
                'type' => 'Literal',
                'options' => array(
                    // Finally, this is what the URL should say to access this route.
                    'route' => '/articles',
                    'defaults' => array(
                        // And of course, we define our default controller and action.
                        'controller' => 'Articles\Controller\Index',
                        'action' => 'index'
                    )
                )
            )
        )
    ),
    // Specify our controller shortcuts (from the controller above)
    'controllers' => array(
        'invokables' => array(
            'Articles\Controller\Index' => 'Articles\Controller\IndexController'
        )
    ),
    // and, finally, where to look for our main file when the /articles link is hit.
    'view_manager' => array(
        'template_map' => array(
            'articles/index/index' => __DIR__ . '/../view/articles/index/index.phtml'
        )
    )
   
);

Simply put, this code above will direct any calls that come in to the right logic in the code and the right template file to use when rendering.

Next, our Controller file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// /module/Articles/src/Articles/Controller/IndexController.php
// Our namespace to define module and usage
namespace Articles\Controller;

// load this for basic controller functionality
use Zend\Mvc\Controller\AbstractActionController;

// define our class for this Controller
class IndexController extends AbstractActionController
{
    // And... define our main action.
    public function indexAction()
    {
       
    }
}

And that’s it with this one. Basically, the route points to this controller to do any sort of logic, or business logic, and calculations before sending stuff to the template for rendering.

And last, but not least, our view file!!! Yay!

1
2
<!-- /module/Articles/view/articles/index/index.phtml -->
This is my Articles Index file.

That’s it. There really isn’t much to it. This view file will produce a comment of the location and some text that mentions that this is my article index file.

If you could resist through this tutorial and the previous one, you can pretty much build your own Zend 2 modules. Yes, there’s a lot more to learn about Zend, which I’ll slowly be covering in other posts, but for now, to get you started to understand how everything is pulled into Zend to render out some simple pages, this is all you need.

I’m also going to teach you how to load scripts and css files into the header. That’s going to be fun. And later than that, I will be covering AJAX calls and partials.

Don’t forget to remove the /articles route from your Application module. 😉

See you next time!

Zend 2 For Beginners

If you’ve kinda touched Zend in the past and have been scared off like me of the complexity and everything you had to learn about it, I would like to share my Zend 2 experience with you. I’m assuming you have Zend 2 already set up on your local (Zend Server or apache and a project already set up), based on their documentation here:

1
http://framework.zend.com/manual/2.0/en/user-guide/skeleton-application.html

Let’s begin, shall we?

First thing you will notice is the folder structure of the main Application module. It’s the only module in the whole site. Let’s start with that.

Whenever you hit your site url local.mysite.com, you get to see the Zend default index page which resides in the /module/Application/view/application/index/index.phtml folder/file. If you modify this page’s HTML code, you will notice changes whenever you refresh your page. Ok, so this is good. This means that this module works, Zend works, the whole Universe makes sense, for now.

Also notice another piece of information in the /module/Application/config/module.config.php file. This is your routing mechanism. This is an array for your routes. Notice the ‘home’ route. It basically says that if you hit the ‘/’ root site, load up the index action from the Application/Controller/Index controller. Standby. How does it know what this controller is? Scroll down below and notice the controllers array. It holds an array called invokables. Seems familiar? Basically, whatever route you have set up, is pointed to the right controller in here. Make sure you keep this in mind for adding additional routes in the application module, or any module later.

The first thing I did was to create additional routes that load other templates within the Application module. I wanted to create a route for /login. Just to have a login page. The thing about a login page is that it should be accessible from anywhere publicly, so I made it part of the Application module. Making it part of a Profile module, or Authentication module doesn’t make too much sense here since the page is a public page that anyone can access. I might do the same for the registration module.

So, first thing I did was created the route for my /logic link.

1
2
3
4
5
6
7
8
9
10
11
12
13
// /module/Application/config/module.config.php
...
'login' => array(
    'type' => 'Literal',
    'options' => array(
        'route' => '/login',
        'defaults' => array(
            'controller' => 'Application\Controller\Account',
            'action' => 'login-page'
        )
    )
),
...

It’s a Literal because it’s a direct link. I don’t need to pass anything else other than an absolute check for /login in the URL.

Another thing to notice is the defaults. So, basically, this says to point to somewhere and load something by default if the route /login is matched. Don’t rush too fast. You need to add three more things.

1. Insert a pointer to your controllers invokables array:

1
2
3
4
5
6
7
8
9
// /module/Application/config/module.config.php
...
'controllers' => array(
    'invokables' => array(
        'Application\Controller\Index' => 'Application\Controller\IndexController',
        'Application\Controller\Account' => 'Application\Controller\AccountController'
    ),
),
...

2. Set up a new Controller in the /module/Application/src/Application/Controller/ folder. Keep the name as the invokable above: AccountController.php. Add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// /module/Application/src/Application/Controller/AccountController.php

// This is to let the application know where this controller is located.
namespace Application\Controller;

// Default Zend Abstract Controller
use Zend\Mvc\Controller\AbstractActionController;

// Your Controller Class (Name should follow the same convention as above). This also extends the default Abstract Controller.
class AccountController extends AbstractActionController
{
    // Keep the name as in your route's action, replacing the dash with uppercase.
    // login-page becomes loginPage, and add Action so zend knows this is the action for the specified route.
    public function loginPageAction() {
        // Your logic code here.        
    }

}

And now, for the template that you’ll be using. By default, Zend will look for the template based on the action specified in your routes. So, it will look for this file: /module/Application/view/application/account/login-page.phtml

Notice the login-page naming convention. It’s good to keep this the same to avoid further confusion. If this page is blank, you will only see the default Zend header and footer.

And now, load your page. If it didn’t work, go back through the steps, and if it still doesn’t work, leave a comment on how you fixed it.

** Next step **

Let’s add some dynamic behavior. Let’s pass in some variables and play around with getting route information from Zend itself.

One thing to notice here is that our routes will change slightly.

Add the below code under your previous “login” route.

1
2
3
4
5
6
7
8
9
10
11
12
13
// /module/Application/config/module.config.php
...
'articles' => array(
    'type' => 'Segment',
    'options' => array(
        'route' => '/articles[/][:id]',
        'defaults' => array(
            'controller' => 'Application\Controller\Account',
            'action' => 'test-with-param'
        )
    )
),
...

We will call this the /articles link, as in news, or blog posts. It could be whatever you wanted, of course, but for now, we’ll play with articles.

Notice our “Literal” has become a “Segment” route. This means that the route will be broken up into little pieces and dynamic stuff will be added to it.

This could be moved into an “Articles” module, which we will later, but for now, we’ll keep it as part of our app, since this, just like the login page, is going to be accessed on our main site.

We don’t need to add anything to our controllers invokables, because we’re calling the same controller. let’s look at our AccountController.php file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// /module/Application/src/Application/Controller/AccountController.php
...
public function showArticlesAction() {
    $routeMatch = $this->getEvent()->getRouteMatch();
    $params = $routeMatch->getParams();
   
    $query = $this->params()->fromQuery();
   
    return array(
        'params' => $params,
        'query' => $query
    );
}
...

Notice something not right here? That’s right, we’re putting article stuff in our AccountController.php Controller file. Articles have nothing to do with accounts, so, we should probably move this function out of here. For now, just to write some spaghetti code that we will learn to refactor later, let’s leave it here.

Notice what’s happening in this controller action. We’re setting some variables that we return in an array. This array will contain a key / value pair that coincidentally have the same name. The keys will become variables in our template that we get to write out, or loop through. Example: the ‘params’ key will become a variable “$params” for the template to use. Let’s see how that looks.

1
2
3
4
5
6
7
8
9
// /module/Application/view/application/account/show-articles.phtml
<div>
    Test With Param
   
    <pre>
        <?php print_r($params); ?>
        <?php print_r($query); ?>
    </pre>
</div>

And when we hit the url: /articles, we should see a nicely formatted list of our variables.

Next post, I will go through the process of moving this feature into our very own Article module.

Comments always welcomed.