MVC.. What the heck is that?

Welcome back!

Welcome to the second article in my series on PHP frameworks. I trust you followed the first article OK and you are all fired up to take your knowledge to the next level.

If you didn’t get a chance to read the first article, it can be found here.

 

Help! What is all this MVC stuff?

Imagine this, you’ve just read 3 or 4 posts online about PHP frameworks and you can see from what most people are saying that it could be the way to go for your next project.

You download the framework, get it installed and then…

“What the hell do I do next?”

One of the most common areas where there is a ton of confusion over PHP frameworks is how they actually work. What exactly is the structure?

You may have seen acronyms such as MVC being bandied around, and while you go ahead and Google it, your brain is still a bit scrambled!

But you can relax. While the structure of PHP frameworks are complex, the actual basic architecture of most of the frameworks out there can be explained quite simply. Oh, and we’ll get onto MVC in just a minute.

 

A trip back in time…

If you have ever worked with HTML as well as your PHP coding (and the chances are quite high that you have) you will at least have heard about separating the content from the code. That is, keeping the HTML separate from the PHP code. This is something that has been strongly advocated for a very long time, right?

Of course, as PHP started life as a simple scripting language, it intertwines with HTML very well. But you will know from the times when you have chucked bits of PHP in amongst HTML, and then perhaps sprinkled some JavaScript in there for good effect, that if it doesn’t work it can be a nightmare to track the bugs. And, if you have several pages you may end up copying and pasting code between them.

You will also know, I’m sure, that inline CSS went out with ark and we all keep our styles separate from our HTML.

So how can this little walk back in history help us? If we look at why we are told to separate our display and styles from our coded logic, we can get a pretty good idea of how we would go about designing a framework.

Why separate?

Spend the next few moments thinking about why you think it is a good idea to separate the display code (HTML for example) and the functional code (PHP, JS etc).

Think back to all the times when you’ve copied and pasted code, then changed it to suit the web page. What about the hours you’ve spent trawling through a mix of code to find out why it just won’t show the data correctly (or even retrieve it in the first place).

As you look at the pile of spaghetti code in front of you, you are reminded of why we should separate the different areas of our web app or website.

So apart from being being a lot easier to read, some of the benefits of separating the code are:

  • Faster and easier to find bugs
  • Avoid repeating our code – DRY: Don’t Repeat Yourself
  • Easier to change the part that displays – or to change the part that does the functional stuff.
  • Easier for someone else to come along and maintain the app or site
  • Easier to get help from others
  • Easier to…

Did you spot it? There seems to be a recurrence of the word “easier” in the above list…

OK, all very good – but what about MVC?

MVC stands for ModelViewController. Quite simply, it is how the majority of modern PHP frameworks separate out parts of the code. The MVC architecture has been around since 1979, so it is a well-proven way of organising stuff.

Model

This has to do with your data. More specifically, the Model deals with getting and saving the data according to the business rules that we set for that data. It interacts with the database (or files) and contains the logic for doing so. This can seem a little daunting at first, but panic ye not – we’ll simplify it all down in a minute.

 

View

The View is as it sounds and is concerned with the display aspects. In other words, it deals with the output to screen or rendering the user interface.

 

Controller

The Controller binds everything together and acts as a router. It takes input from the user, interacts with the Model and instructs the View to update.

To give an example of how this works, we can take a typical web request:

  • The browser (via user input) sends a request to the server
  • This is the trigger for the controller to do something with the request (often called an action)
  • The controller then interacts with the model
  • The controller then instructs the view to update and display the correct data

I don’t get this Model thing

The View and the Controller parts of the MVC architecture are relatively straight forward to understand, but the Model does seem to cause confusion. Lets look at some typical models:

User: this may contain the following data fields…

userID

firstname

lastname

emailAddress

Blog Post: this may contain the following data fields…

postID

postText

dateCreated

createdByID

statusID

datePublished

publishedByID

It may at first seem like the models are just the data fields from the underlying data table, but that isn’t necessarily so. The data fields in they model may be all or just some of the fields from the table. The model may also contain fields from more than one table.

In addition to the data fields themselves, the model determines the rules that govern how those data fields are used. For example, applying any filters and queries for subsets of data.

This removes the need for these filters to be applied at the View side of things, and helps to make the code more manageable and re-usable.

 

Right… so MVC is a it clearer now

Good, we have a basic understanding of one of the most commonly supported architectures of a PHP framework. What next?

The different frameworks may have slightly different ways to organise your actual physical files, however all follow a directory structure something along the lines of:

app/

models/

views/

controllers/

 

There may also be a few more folders such as pluginsconfig etc, and this nice separation of the physical files follows the virtual separation of the MVC architecture.

This really does help to keep you organised and simplifies maintenance, bug-tracking and version control.

By now you will be realising how a framework fits together and the basics work. There is more to it, but this foundation knowledge is a great start to shedding some of the skin if confusion that often shrouds frameworks.

 

Summary

In summary then, we have learned that the chosen architecture for most popular modern PHP frameworks is Model, View, Controller (MVC).

We also know that the MVC architecture separates the web app into three logically sound parts:

Model: 

Concerned with getting and setting data according to certain rules that we put in place.

View:

Creates and updates the user interface – the part the user sees on-screen.

Controller:

Routes the requests from the user input to the Model to get/set the data, and then interacts with the View to display that data to the user.

Excellent! I trust this has helped simplify the basic architecture of PHP frameworks for you, and has reduced some of the intimidation of the perceived complexity.

Now you’ve got this far, is a PHP framework for you? We’ve already covered a number of the benefits of using a framework, so perhaps it is time to look at some of the other areas of uncertainty about them.

This is indeed what I’ll cover in my next article… funny that!


To get more of your questions answered, sign up to my newsletter now! Make sure you get all the latest PHP tips and tricks delivered directly to your inbox:

Help – What’s a PHP Framework?!

You break down with hopelessness and despair

Every time you read about PHP frameworks you cry with frustration! Your brain melts with utter confusion. You shrink into the corner feeling completely intimidated!

One time, you even felt brave enough to download a framework. But, you had no idea what the hell to do with it next.

You see people mentioning frameworks all the time on forums, but you also see all the confusion around them. Heck, there is so much misdirection. So much clutter. So much point-scoring over which framework to use that the whole point of a PHP framework has bypassed you completely. You feel like they are a mountain to climb – and you just don’t have the time right now for pursuing extreme outdoor sports. Time is money you know!

 

It doesn’t have to be like that

Just imagine for a moment… What if PHP frameworks were your area of expertise? What if you approached them with confidence, certainty and skill?

What if you based your decision to use a PHP framework for your next project on your complete understanding and knowledge. What if you could easily and expertly apply what you have learned in one framework to any other framework out there?

 

You can become an expert

Start right now! Take take your first steps into the world of PHP frameworks. My series of easy to read and understand articles will guide you. And the best thing – they are completely FREE!

 

 Article 1 starts here!

Let’s get going! Let’s find out what all this PHP framework stuff is all about.

 

What exactly is a PHP Framework?

There is so much confusion over frameworks that you are be forgiven for not having the first clue! And even if you do have an inkling, there is such a mass of discussion on the forums about what frameworks are, what the benefits are, which framework to use and whether they are just libraries or not… the level of confusion and contradictory messages is quite overwhelming.

 

Chill

But you can relax. Take a load off and together we’ll cut through the intimidating technical jargon and simplify everything a bit. So turn the lights down low and snuggle up…

 

Why a framework?

Before we get into what a framework actually is, you may find it easier to approach things from a different angle. Lets first look at some of the problems and pain points that frameworks are supposed to solve.

“I don’t want to have to re-write the same code time and again, I feel like I am just re-inventing the wheel!”

“Arghhh, this code is like a big pile of spaghetti! How am I supposed to do anything with it?”

“I am so scared of writing a PHP app and messing something up, especially security – what if someone hacks my site?”

“Coding standards? Erm, are there such things as coding standards?”

There are a ton of other issues as well, but I’m sure you get the idea. Frameworks in all languages attempt to instil a set way of putting something together (a website, app etc), because (we hope) that the “set way” has been proven to be the best. But what does “best” mean?

In our world of web apps and websites, “best” is generally accepted to mean:

  • Secure
  • Efficient
  • Maintainable
  • Bug-free (or bug-reduced at least)
  • Well supported

Most of us would like to add simple, easy to learn and easy to implement to that list as well. However, we also have to accept that there is a learning curve to anything that ultimately makes things easy (oh the irony!). But thats a subject for a different article.

 

Back to it

So now you know what challenges a framework is designed to solve, and that its chief aim is to provide an environment that encourages “best practice”. Does that get us any closer to finding out what a framework actually is?

Well, yes and no. Yes because we know it is an environment. No because so is coding raw PHP in an IDE without a framework – albeit akin to a plate of your finest Italian stringy pasta at times.

Yes because we are now getting the feeling that it has constraints. No because that doesn’t really tell us anything!

 

You are starting to lose me!

OK, some definitions of a PHP framework that are found in a web search:

“Essentially a framework is the structure that you can choose to build your program on”

“Frameworks provide scaffolding that can allow you to develop faster/more cleanly”

“A PHP Framework in my eyes is a collection of classes which help you develop a web application”

The one I like the best is the one referring to “scaffolding”. Further to this, I see a framework as an environment that provides the core foundation and plumbing for your application.

There is quite a lot of discussion about the collection of classes train of thought, and although in some respects that is true, it is only part of what a framework is.

Any clearer?

 

Wrong question?

Maybe we’re asking the wrong question by asking “what is a PHP framework?”. Perhaps it is just too fuzzy a concept to put a concrete definition on. Perhaps a better starting question is “what can a framework do for me?”

 

So, what can it do?

This again can be quite hard to answer in concrete terms, and can also become quite personal. But, in simple terms a PHP framework can greatly speed up the development of your web application by doing a lot of the grunt work for you.

Aspects where you would normally have to re-write code time and again, such as connections to databases and form validation, are all usually part of the framework. You just put in the correct configuration and away you go.

OK, not quite, but you certainly don’t need to be starting from scratch every time. In fact, many frameworks include CRUD creation. CRUD stands for Create, Read, Update, Delete and is to do with the interaction with the database. A CRUD generator will take your setup and literally generate the underlying code to perform most of the interactions you need to read, write and delete data.

Frameworks also offer many other benefits such as site security, separation of PHP code from HTML (therefore encouraging best practice and easier bug-tracking), and easier future maintenance.

 

I’m scared I’ll lose control!

One recurring theme I see on the forums when people are trying to decide whether to learn a framework or not, is the fear that they will lose control of their code. Although really out of the scope of this article, I felt it important enough to address it here.

The people I see making these comments don’t fully trust somebody else’s code, even if that somebody else is an entire community of developers who have spent the last few years testing and improving the underlying design and coding base.

You may have heard of the term “Not Invented Here”. In fact, many refer to it as a syndrome. The “Not Invented Here” syndrome sufferers are those that simply don’t want to put trust in the work of others. Usually, this stems from this fear of losing control and is the exact opposite of “invented Here” or “Proudly Found Elsewhere”.

When time is money and you are running your own business writing websites or developing web applications (or your boss is breathing down your neck on your latest project), I don’t believe you can afford to take the “Not Invented Here” approach.

Of course, you should have the underlying core skills and carefully select the framework you do use, but to take a purist stance on this is only hurting your financial health.

That’s all I’ll say on this for now, but if you fit into this group of people then perhaps you should really look at how much maintaining this attitude is actually costing you.

 

Moving on

There are many benefits to PHP frameworks that we’ll cover in future articles, but for now let’s summarise what we already know.

  • A PHP framework is a structured development environment designed to encourage best practice.
  • A PHP framework provides the core foundation and plumbing to perform many of the functions you usually want to do with your web app or website.
  • By creating a usable, secure and largely reliable scaffold, the speed and ease with which you can develop your site or app is greatly increased.
  • As a small business owner, using a PHP framework can shorten the time to completion and therefore increase your profit and/or help you to become more competitive.
  • As an employed developer, a framework can make your job a whole lot easier by removing the need to continuously re-invent the wheel.

 

What next?

Now that we are getting a good grounding of what a PHP framework is and some ideas on how it can help us, we need to look at one of the most confusing areas for a lot of people: the structure of a PHP framework.

This is the subject of my next article on PHP frameworks, which is coming very soon.


To get more of your questions answered, sign up to my newsletter now! Make sure you get all the latest PHP tips and tricks delivered directly to your inbox:

7 easy ways to get your questions answered

Arghhhh – Just Help Me!

Have you ever got so frustrated when no-one answered the PHP question you posted that you just felt like giving up?

For some of us, finding the time to learn PHP (or any other language for that matter) is a downright struggle. We’ve been tasked with getting our project or assignment complete and quite frankly, we don’t have the time to learn everything we need to know about coding – that’s what forums are for right?

Well, just like you I’ve had posts without any answers – and it hurts! Many of my questions have been in desperation as I’ve been battering my head on my desk after spending several hours failing to find a solution. As if I wasn’t mad enough as it is, after posting my forum question nobody answers! And then…

Was that comment really necessary?

Worse still, some so-called expert chips in a very unhelpful comment about me not including code tags in my post. Eh, what? Its usually followed-up with “we are very happy to answer your questions if you help us by posting it correctly”… help, how do I do that?

But wait, there is love in the air…

Here’s the thing though, all the experts that answer questions on the forums do it because they love it. They absolutely love helping other people. They get their kicks from sharing what they have spent hours and hours and hours learning, experimenting with and testing, testing, testing.

Just look at how many questions they all answer, every day, every week! So many of the experts have been on the forums for years, and it doesn’t matter whether this is your very first question, whether you are a beginner, just dipping into PHP to complete that project, or a seasoned coder – they actually want to help you! That’s right, they actually do!

Erm, OK, then why….

You may now be wondering…

“So why didn’t they answer my post then?”
“English is not my first language, why do they penalise me for that?”
“I’m brand new to PHP and to forums, I just don’t know where to start”

They are banging their heads as well!

And do you know what? The experts are just as frustrated as you are! They are itching to help you but they can’t. They are also banging their heads on their desks because they just cannot even start to solve your problem.

On a forum I read regularly, one expert was so mad he said it made his “blood boil!”. Wow, he was one angry expert.

Wahoo, here’s the best bit!

The good news is that it is so easy for all that frustration to just melt away. In fact, there is no need for it to be there at all.

The even better news is that you, yes even you, can get your questions answered by the experts. And, all in good time for you to finish your project. In fact, they will be answering your questions before anybody else’s!

After trawling through hundreds and hundreds of forum posts, and reading and listening to what the experts themselves have to say, I have compiled a simple 7-point check list that you can use right now to get the answers you need. I’m sure the experts can expand on this even more, because like you I’m still learning every day. If you are an expert, I want to help you too so let me have your suggestions!

Here’s the checklist

  • Read the forum rules and guidelines
  • Give the context and be specific
  • Post the error message
  • Describe the behaviour
  • Comment your code
  • Use code tags
  • Include line numbers

Pretty simple isn’t it!

Here is a PDF version for you to download, print off and keep.

If you want a nicer looking A5 version, its here!

Please feel free to share with whoever you wish!

And here’s a bit more info on each point


Read the forum rules and guidelines
Almost every forum has a set of rules and guidelines. Often, these are in a “pinned” post and highlighted…

Forum rules
Pinned post example

Sometimes you need to choose a menu option or tab to see the rules and guidelines…

Forums rules
Menu navigation to rules

However they are shown, if you want your questions answered then you need to be following the rules.

Give the context and be specific
The more specific you are about what it is you are trying to achieve, and exactly what the nature of your issue is, the quicker your question will get answered.

At all costs, avoid phrases like “it doesn’t work”, “it won’t run”, “what’s wrong with my code”. Unless you’ve been specific and given context, these phrases mean nothing and just really makes the experts mad!

Include the error message
If you have an error message from your code, include it exactly as it is. This is a huge help to anyone trying to solve your problem.

Describe the behaviour
What behaviour do you want the code to be doing? Let them know!
What behaviour is it actually displaying? Let them know!

Comment your code
Even a couple of well chosen words to comment a line or block of code can really help with the debugging process. If the experts know what you are trying to achieve and what you think the code should be doing, they can help you faster.

Use code tags
When including your code in your forum post, it is important that everyone can read it correctly. After you have posted your question, many forums also allow the code to be shown in a separate popup or even to be printed. This is a huge help to anyone trying to solve your issue. But it probably won’t work properly if you don’t use code tags. What are code tags?

Here is an example for posting on the Dream In Code forum:

Dream In Code also accepts [php] [/php] tags around your code.

Similarly,  the PHP Freaks forum also uses [code] [/code]  and [php] [/php] tags.

The individual forum guidelines will always let you know what tags are accepted.

Include line numbers
If your IDE/coding tool displays line numbers, include these with your code fragment. Again, this is a huge help to responders, especially if the error message points to a specific line.

Here’s the link to the PDF version of the checklist again

Here is the colourful A5 version

And finally…

Although the experts love to help you, they also want to see you helping yourself. The more they see that you are thinking for yourself as the problem unravels and solutions appear, the more they are likely to continue helping. Here are some of the things they say:

“Don’t be afraid to experiment!”

“Make mistakes”

“Become a contributing part of the team”

“Take our suggestions and yes, try them, but then come up with your own”

If you are afraid that you will lose your work or break something if you experiment, then copy and paste it into a text editor before you make changes, or use source code control for this.

Here’s the link to the PDF version of the checklist again

Here is the colourful A5 version

Huge Free Bonus!

One huge added bonus that you get completely free by following the check list, is that it will start you on your way to effective debugging. Just think about how much time you will save when you can spot the errors yourself! Not only that, but your learning will be accelerated and your project will be completed that much quicker and painlessly!

 

Some Other Resources

I’ve received some really good additional resources about this subject and think its a great idea to share them:

http://blog.jondh.me.uk/2012/09/how-to-use-stack-overflow/ http://slash7.com/2006/12/22/vampires/ http://whathaveyoutried.com/


To get more of your questions answered, sign up to my newsletter now! Make sure you get all the latest PHP tips and tricks delivered directly to your inbox:

Removing the bad smell of global variables

There is always a lot of discussion about good coding practice in PHP, and considerable disagreement when it comes to some areas.

It can be really quite confusing, especially when learning PHP, and many of us just take the easy option because we can’t find agreement on an alternative.

Fortunately, there are some areas where there is general consensus on the best way forward. Global variables is one such area.

Why shouldn’t I use global variables?

While using global variables can seem very easy and convenient, they are often viewed as bad coding practice in PHP for several reasons:

  • They make debugging harder
  • You can get  unexpected results if they are modified without other parts of the code knowing
  • It can make code less portable
  • Security can be compromised

What’s that smell?

So, global variables can lead to a bad code smell and we all know that everyone wants to avoid unmanageable and badly designed code.

But what’s the alternative?

Keeping it simple

One of the easiest ways is to pass the values to your function using parameters. So instead of code that uses global variables like this:

 

We can pass values to the function like this…

 

Here, the variables are local only to the function and this makes debugging in particular, much much easier.


Whether you found this post removed a bad smell for you, or made you smile knowingly, sign up to my newsletter to make sure you get all the latest tips in your inbox:

 

Super-quick tip to save time debugging

We all know that debugging PHP can be (ahem) a challenge… You can make your life a little easier by putting a couple of lines at the top of your script:

<?php
error_reporting(E_ALL);
ini_set(“display_errors”, 1);

Wow, that was easy!

Get lots more easy PHP tips and tricks directly to your inbox by signing up to my newsletter:

One easy way to select earlier dates in MySQL

I recently read a post asking how to select entries in MySQL based on a date field. The original poster only wanting to choose those records that were newer than 7 days old.

This seems quite a common challenge that new PHP coders have, so here is an easy way to achieve it.

  • Firstly, check the date field is indeed a date (or datetime) field and not a varchar. Date comparisons cannot be done on varchar fields
  • Use the MySQL function: DATE_SUB(date, INTERVAL expr units)

One example is:

SELECT myField FROM myTable WHERE myDateField >= DATE_SUB(CURDATE(), INTERVAL 7 DAY);

However if the date field you want to use is actually a DateTime field, the above code may not work as the time throws things. In this case, you need to just be using the date part. For this we can use the MySQL DATE() command. So, the query now looks like this:

SELECT myField FROM myTable WHERE DATE(myDateField) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY);

Here is the link for the official docs on DATE_SUB() and DATE_ADD();

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add

 


 

If you found this post helpful, sign up to my newsletter and get PHP tips sent directly to your inbox:

 

How secure is storing your MySQL connection data in a separate file?

Storing your MySQL database connection information in a separate file is secure and safe as long as you follow best practice:

  • The file must have a .php extension
  • All the connection information should be inside your PHP code, and none of it should be output to the browser.

If the file has the .php extension, it will be run as server code and is not visible to any would-be snoopers as there is no client-side output.

You can test this yourself by pointing your browser to your connection file (e.g. www.yourdomain.com/yourconnectionfile.php).

Make sure there is no browser output and check the page’s source code. If it is just a blank page then all is good.

If you see any of your connection data, you will need to check the above two points have been implemented correctly.

A further recommendation would be to locate the connection file in a folder that cannot be accessed publicly. Often, this can be a folder on your web server higher up in the tree that is accessible to the scripts but not the public.


If you want PHP tips and tricks delivered directly to you, make sure you sign up to my newsletter: