Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 14 ■ MVC ARCHITECTURE^207

Creating an MVC Framework.


At this point, you will need to start creating directories. I recommend the following layout:

> cd /usr/local/www/yourdomain.com
> mkdir document_root/images document_root/styles
> mkdir –p application/models application/views \
> application/controllers
> find

.

./document_root
./document_root/images
./document_root/styles
./application
./application/models
./application/views
./application/controllers

Next, create a placeholder for your bootstrap file, as shown in Listing 14-1.

Listing 14-1. Creating the Bootstrap index.php

> pico document_root/index.php

Hello, World!

At this point, reloading your browser should result in “Hello, World!” being shown. Navigate to
http://yourdomain.com/nonexistent. You should get a 404 File Not Found error.
For this MVC framework to work, you need every single request to hit this index.php. To do
this, you enlist mod_rewrite through an .htaccess file, as shown in Listing 14-2.

Listing 14-2. Using mod_rewrite in an .htaccess File

> pico document_root/.htaccess

RewriteEngine on
RewriteRule !\.(js|gif|jpg|png|css)$ index.php

Reload your browser, and you should see “Hello, World!” If you don’t, you will need to
ensure that your server has mod_rewrite available and does not restrict .htaccess overrides
with a nonstandard allowOverrides directive.

Bootstrapping
The next stage in this process is to create a bootstrapping script in your index.php file. This file will
be responsible for including files and initializing the front controller. Most MVC frameworks will
use SPL autoloading mechanisms to load files, but for simplicity, you will just require_once for
now. Create the file as shown in Listing 14-3.

McArthur_819-9C14.fm Page 207 Thursday, February 28, 2008 7:44 AM

Free download pdf