changed to controllers

This commit is contained in:
Patrick 2014-11-30 21:06:11 +01:00 committed by lubiana
parent 3dd32558a0
commit fc4dea1873
4 changed files with 28 additions and 29 deletions

View file

@ -2,20 +2,22 @@
### Dispatching to a Class
In this tutorial we won't implement [MVC (Model-View-Controller)](http://martinfowler.com/eaaCatalog/modelViewController.html). MVC can't be implemented properly in PHP anyway, at least not in the way it was originally conceived. So forget about MVC and instead let's worry about [separation of concerns](http://en.wikipedia.org/wiki/Separation_of_concerns).
In this tutorial we won't implement [MVC (Model-View-Controller)](http://martinfowler.com/eaaCatalog/modelViewController.html). MVC can't be implemented properly in PHP anyway, at least not in the way it was originally conceived. If you want to learn more about this, read [A Beginner's Guide To MVC](http://blog.ircmaxell.com/2014/11/a-beginners-guide-to-mvc-for-web.html) and the followup posts.
Instead of just calling everything a controller, let's give our names descriptive names that describe what the class actually does. In this case, we will just display content, so a fitting name would be `Presenter`. If the class does something else, we will name it accordingly.
So forget about MVC and instead let's worry about [separation of concerns](http://en.wikipedia.org/wiki/Separation_of_concerns).
Create a new folder inside the `src/` folder with the name `HelloWorld`. This will be where all your hello world related code will end up in. In there, create `HelloWorldPresenter.php`.
We will need a descriptive name for the classes that handle the requests. For this tutorial I will use `Controllers` because that will be familiar for the people coming from a framework background. You could also name them `Handlers`.
Create a new folder inside the `src/` folder with the name `Controllers`.In this folder we will place all our controller classes. In there, create a `Homepage.php` file.
```php
<?php
namespace Example\HelloWorld;
namespace Example\Controllers;
class HelloWorldPresenter
class Homepage
{
public function helloWorld()
public function show()
{
echo 'Hello World';
}
@ -28,10 +30,7 @@ Now let's change the hello world route so that it calls your new class method in
```php
return [
['GET', '/hello-world', [
'Example\HelloWorld\HelloWorldPresenter',
'helloWorld',
]],
['GET', '/', ['Example\Controllers\Homepage', 'show']],
];
```
@ -52,6 +51,6 @@ case \FastRoute\Dispatcher::FOUND:
So instead of just calling a method you are now instantiating an object and then calling the method on it.
Now if you visit `http://localhost:8000/hello-world` everything should work. If not, go back and debug. And of course don't forget to commit your changes.
Now if you visit `http://localhost:8000/` everything should work. If not, go back and debug. And of course don't forget to commit your changes.
[<< previous](5-router.md) | [next >>](7-inversion-of-control.md)