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?

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.

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. ;)