Category Archives: Frameworks

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: