The Slim Micro Framework for PHP 5 is a micro framework that enables developers to quickly write RESTful web applications and APIs. I emphasize micro because Slim is just that — a lightweight and nimble PHP framework used to build smaller web applications and APIs. Unlike CodeIgniter and Symfony (excellent frameworks created by EllisLab and Sensio Labs, respectively), Slim forgoes controllers and abstract components for simplicity and ease-of-use.
You can build a Slim Framework web application with only a single file. Over time, however, projects grow in scope and size; better organization becomes necessary. Slim does not use controllers to organize application methods or routes; controllers are beyond Slim’s concern. That being said, it is possible to organize larger Slim Framework applications. Here’s how I organize my own Slim Framework applications.
Here’s the directory structure I use for my own Slim Framework applications:
public_html/ .htaccess index.php styles/ images/ scripts/ app/ routes/ session.php member.php admin.php vendor/ lib/ data/
Contains the Slim Framework’s .htaccess and index.php. files. The index.php file is where you instantiate and run your Slim Framework application. Public assets (stylesheets, images, and scripts) are in this directory, too.
Contains the application’s code that should not be available in the public document root.
Contains my own custom libraries used by my application.
Contains the application’s database schema and (if needed) SQLite databases.
Organize routes into separate files
An example Slim Framework application may have an admin control panel, members-only pages, and public pages
(e.g. log in, log out, and register). As shown in the filesystem layout above, I separate related routes into
separate files. Admin routes go into
app/routes/admin.php. Member routes go into
management routes (e.g. log in, log out, register) go into
app/routes/session.php. These separate route files are
public_html/index.php like this:
<?php $app = new Slim(); require '../app/routes/session.php'; require '../app/routes/member.php'; require '../app/routes/admin.php'; $app->run(); ?>
Instead of having one very large
index.php file, there are several smaller files that make building a
larger Slim Framework application much easier.