drew.d.lenhart

programming, software, technology, anything on my mind...

PHP App using Slim, Eloquent ORM, and Twig Template Engine - Part 1

2016/01/25

I spent the last few years completely ignoring the slew of PHP Frameworks out there ( Hey, I like to re-invent the wheel sometimes ). I finally realized that I've been getting sloppy in some of my small projects that turn large. Specifically my own solutions to problems when I could have just used a framework and saved loads of time. I also noticed I've been mixing PHP code with HTML code way too much and is becoming harder to maintain. It was time for me to embrace something new that could be beneficial in the long run.

I started using the Slim Framework awhile ago and really like it, as it was super easy to start a micro project on the fly! From here I began using it mostly as a URL router and began mixing in my own Database helpers to make my life easier. But in the long run, it wasn't enough to keep the multitude of SQL queries getting mixed with PHP/HTML code in a un-organized fashion.

slim-logo

I began to start tinkering with a mixture of frameworks; Slim, Eloquent, Twig and Composer as the package manager. This is the combination I like best and will use as a basis for this article series.

-Eloquent ORM is a Object-relational mapping framework mostly used in another big time framework called Laravel. Whats great about this package is that Eloquent isn't tied to Laravel and can be used without it. We can create models that represent tables in a database and use the framework to easily manipulate data!

-Twig is a easy to use PHP template engine.

-Composer is a dependacy manager for PHP that will install and update libraries.

I'll quickly show how to get the project started creating a "Blog" application.


Composer

On a local development environment, create the folders and files like below:

Screen Shot 2016-01-24 at 8.05.43 PM

Edit the composer.json to include Slim, Eloquent, SlimView, and Twig:

{
    "require": {
        "illuminate/database": "*",
        "slim/slim": "~2.6",
        "slim/views": "~0.1",
        "twig/twig": "1.*"
    }
    }

Follow the directions on the Composer website to get Composer installed on your system. When set up, CD into the root of the newly created folder and type:

composer install

This command will install all the necessary packages in a generated vendor folder. **Note, when adding packages at this point, use composer update to add additional packages.


Slim

Now that we have all the necessary packages, we can begin by setting up a home route. Keep in mind, Slim will act as our Controller/Url router, Eloquent is our Model/Database Object-relational mapping, and Twig will be the View! MVC, Model, View, Controller!

Open index.php in your favorite text editor or IDE. In the world of Slim, index.php IS the App!

//Composer autoload
require 'vendor/autoload.php';

SlimSlim::registerAutoloader();

$app = new SlimSlim();

//Main page
$app->get('/', function() use($app) {
    echo "This is the main page!";
});

//RUN!!
$app->run();

Depending whether you are running this app on Linux or Windows, we will need to route all traffic to this index.php file. For Linux, create a .htaccess file and place in the root directory along with index.php.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

See more information about turning on the mod_rewrite in Apache. This is pretty essential to allowing us to use CLEAN urls in Slim. If you don't use this option, keep in mind, you will have to use something like the following:

http://localhost/index.php/about or http://localhost/index.php/posts/1

As opposed to having a much cleaner url of:

http://localhost/posts/1 Both options will work just fine.

If you are on Windows, this web.config file will take the place of a Linux .htaccess file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="slim" patternSyntax="Wildcard">
                    <match url="*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
    </configuration>

** The URL rewrite module needs to be installed on IIS for this to function!


If all is set up correctly, you should be able to access http://localhost in your browser, or wherever you have the folder located and see some text on the screen!

Now that the basics are done, in the next posting, I will cover:

  1. Inserting some mock data into a MySQL database.
  2. Modify the "/" get route above to pull article listings using Eloquent.
  3. Create another route to view individual listings.
  4. Create the standard CRUD routes.

Thanks for reading!

--Drew