Jonnie Grieve Digital Media: Blog

Home
by on 27th April, 2023 - 10:23am (0)

Blog: Slim – The PHP Framework (More Posts)

My next little project/investigation is to get something with the PHP Slim Framework back up and running, As I start to write this there are 2 links up right now

https://projects.jonniegrieve.co.uk/slimmin/
https://projects.jonniegrieve.co.uk/slim

And neither is working.

To stretch my wings and try to refresh my memory a bit I asked ChatGPT to get me started with a small project with some routes that render a template.

input: can you make me a starter project using the slim framework

Install composer and check the latest version is running  (c2.5.5 as of this date)

composer -v

https://projects.jonniegrieve.co.uk

There are 2 projects on my space as I begin working on this.

  • https://projects.jonniegrieve.co.uk/slimmin/
  • https://projects.jonniegrieve.co.uk/slim

Neither is working.

I’m going to try to refresh this project and try and get something going, at least in local development, but I’d like to try and deploy what I do get done to the web.

First, I’ll create a directory for the project to go in.

mkdir slim

And, making sure I have the latest version of Composer, installed,

composer create-project slim/slim-skeleton slim-project

I created a new [rpokect instance so slim-project would be the project route. Which created the project with no security vulnerabilities which is nice.

run composer install if you’re installing to a new location via git.   (it gets the dependency information from the composer.json file).

let’s examine the project structure

The Slim project has the following directories

vendor/  – This is the place dependency files are location.  if you need to insrall your project again to a new directoy the dependencies will be downloaded again to this folder. So the folder should be ignored in .gitignore for the purposes of version control.

public/ – the place where the markdown or php files that make up the project are stored.

app/ – project resources, routes, and middleware go in this folder.

log/ – log files are written to this directory for debugging.

And when you have installed it there’s a composer.json file.

When everything is set up, Slim will get you started with a default application. To test it, make sure you’re in the project root and start a local development server.

php -S localhost:8000 -t public

And verify in your browser by going to http://localhost:8000/

There are 2 things you can do to get data printed on the screen.

First, a get() route that writes a simple message to the screen

<?php
$app->get('/', function (Request $request, Response $response) {
$response->getBody()->write('Hello world!');
return $response;
});

Or I can try and make a route that gets the contents of a PHP file

// get contents of index file
/*$app->get('/file/{filename}', function ($request, $response, $args) {
$filename = $args['filename'];
$file_path = __DIR__ . "/path/to/files/{$filename}.php";
$file_contents = file_get_contents($file_path);

$response->getBody()->write($file_contents);

return $response;

Use routes, middleware, and Remder templates using Twig.

What I’m getting at is I want to make a simple website using the Twig framework. And that involves rendering template files.

Let’s add Twig to the project.

composer require slim/twig-view

The composer.json file should now look something like this.

{
"name": "slim/slim-skeleton",
"description": "A Slim Framework skeleton application for rapid development",
"keywords": [ ],

...

"require": {
"php": "^7.4 || ^8.0",
"ext-json": "*",
"monolog/monolog": "^2.8",
"php-di/php-di": "^6.4",
"slim/psr7": "^1.5",
"slim/slim": "^4.10",
"slim/twig-view": "^3.3"
},

...
}

simple project setup instructions for setting up a simple website with Slim.

  • Set up a Slim application
  • Define your routes for each page of the website
  • RenderTemplates
  • Serve Static files
  • Add middleware
  • Test website
<!DOCTYPE html>
<html>
<head>
<title>Hello {{ name }}</title>
</head>
<body>
<h1>Hello {{ name }}</h1>
<p>Welcome to my website!</p>
</body>
</html>

Twig routes

use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;

// Create a Twig instance
$twig = Twig::create('path/to/templates', [
'cache' => 'path/to/cache',
]);

// Add Twig middleware to your Slim app
$app->add(TwigMiddleware::createFromContainer($app, $twig));

We need to render templates.  There are 3 pages in this simple example. So I’m going to create 3 templates and a layout template.

  • home.php
  • about.php
  • contact.php
  • layout.php
<!-- templates/layout.php --> 
<!DOCTYPE html> 
<html> <head> 
<meta charset="UTF-8"> 
<title>{% block title %}My Website{% endblock %}</title> 
</head> <body> {% block content %}{% endblock %} </body>

Fatal error message

Fatal error: Uncaught TypeError: 
Argument 2 passed to Slim\Views\TwigMiddleware::createFromContainer() 
must be of the type string, 

I suspect there may be some compatibility problems with the machine I’m working with.  I can’t even get the most simplest of routes together.

Let’s take a step back and strip away the middleware.

Let’s first create the simplest Hello World Application

<?php

use Slim\Factory\AppFactory;
use Slim\Routing\RouteCollectorProxy;

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

$app = AppFactory::create();

$app->get('/', function ($request, $response, $args) {
$response->getBody()->write('Hello, world!');
return $response;
});

$app->run();

This is the simplest of apps that contains 1 route.  Routes are HTTP requests in Slim that perform one action, which is to return a response. In this case, it’s a get route that returns a HTTP response to the project route and writes text to the screen.  There’s no markup or HTML doctype. Not very exciting.

A set of pages, that are routes that return a response.

$app->get('/', function ($request, $response, $args) {
return $this->get('view')->render($response, 'home.php');
});

Conclusion.

I’m going to leave the blog there for now. After running into plenty of roadblocks in trying to get some connected routes together, I’ve settled upon one working, get() route It’s clearly been some time since I did some coding with Slim, and working practices with Slim and Twig for render templates may have moved on since I last did some work with it. And I had hoped to put something together on my web server but deployment isn’t as straightforward as I remembered either.

Links for Further reading

 

This post has been assigned to the following categories

    Leave a Reply

    Your email address will not be published. Required fields are marked *