jupitern/slim3-core-skeleton

This package is not installable via Composer 1.x, please make sure you upgrade to Composer 2+. Read more about our Composer 1.x deprecation policy.
There is no license information available for the latest version (1.0.1) of this package.

1.0.1 2020-01-10 13:11 UTC

This package is auto-updated.

Last update: 2020-07-31 00:38:03 UTC


README

slim3-core-skeleton

project boilerplate starting point.

Install the Application

Run this command from the directory in which you want to install your new Slim Framework application.

php composer.phar create-project jupitern/slim3-core-skeleton [my-app-name]

Replace [my-app-name] with the desired directory name for your new application. You'll want to:

  • Point your virtual host document root to your new application's public/ directory.
  • Ensure storage/ is web writable.
  • make the necessary changes in config file config/app.php

Run it:

  1. $ cd [my-app-name]\public
  2. $ php -S localhost:8080
  3. Browse to http://localhost:8080

Key directories

  • app: Application code (models, controllers, cli commands, handlers, middleware, service providers and others)
  • config: Configuration files like db, mail, routes...
  • lib: Other project classes like utils, business logic and framework extensions
  • storage: Log files, cache files...
  • public: The public directory contains index.php file, assets such as images, JavaScript, and CSS
  • views: Views (html code...)
  • vendor: Composer dependencies

Routing and dependency injection

The app class has a route resolver method that:

  • matches and injects params into the controller action passed as uri arguments
  • looks up and injects dependencies from the container by matching controller constructor / method argument names
  • automatic Resolution using controller constructor / method argument types
  • accepts string or Response object as controller action response

Example defining two routes for a website and backend folders:

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

// simple route example
$app->get('/hello/{name}', function (Request $request, Response $response, $args) {
	$name = $request->getAttribute('name');
	$response->getBody()->write("Hello, $name");

	return $response;
});


// example route to resolve request to uri '/' to \App\Http\Site\Welcome::index
$app->any('/', function ($request, $response, $args) use($app) {
	return $app->resolveRoute([\App\Http\Site::class, "Welcome"], $args);
});


// example using container resolution and automatic resolution (auto-wiring)
// resolves to a method to the controller \App\Http\Site\TestController
// injects the :id param value into the method $id parameter

// route definition
$app->any('/test/{method}[/{id:[0-9]+}]', function ($request, $response, $args) use($app) {
	return $app->resolveRoute([\App\Http\Site\TestController, $args['method']], $args, true);
});

// Controller Welcome definition
namespace App\Http\Site;
use \App\Http\Controller;

class Welcome extends Controller
{
	public function index($id, \Psr\Log\LoggerInterface $logger, \App\Model\User $user)
	{
	    $logger->info("logging a message using logger resolved from container");

	    $logger->info("getting a eloquent user model attributes using automatic resolution (auto-wiring)");
	    debug($user->getAttributes()); // helper method debug

        // return response as string. resolveRoute method will handle it and output the response
	    return "id = {$id}";
	}
}

Console usage

  • Usage: php cli.php [command-name] [method-name] [parameters...]
  • Help: php cli.php help

How to create a new command:

  1. Create a class under directory app\Console in namespace App\Console
  2. Your class should extend \App\Console\Command
  3. create a public method with some params.
  4. DONE!

Example:

Command class:

namespace App\Console;

class Test extends Command
{

	public function method($a, $b='foobar')
	{
		return
			"\nEntered console command with params: \n".
			"a= {$a}\n".
			"b= {$b}\n";
	}
}

Execute the class:method from command line:

// since param "b" is optional you can use one of the following commands

> php cli.php Test method a=foo b=bar

> php cli.php Test method a=foo

Code examples

Get application instance

$app = \Jupitern\Slim3\App::instance();
// or simpler using a helper function
$app = app();

Helper functions:

// Debug a variable, array or object using a debug helper
debug(['a', 'b', 'c']);
// or debug and terminate app passing true as second param
debug(['a', 'b', 'c'], true);
// get base app url
url();
// add a message to monolog
addLog(\Psr\Log\LogLevel::ERROR, "test message");
// add message to request log trace
addTrace("message");

Get and set config values

$val = app()->getConfig('app.testSetting', 'defaultValue');
app()->setConfig('app.testSetting', 'value');

Query db with eloquent

$db = app()->resolve('db');
$db->table('users')
    ->select('id', 'name', 'username')
    ->where('id', $userId)
    ->where('name', 'Nuno')
    ->first();

Send a email using PHPMailer service provider and default settings

/* @var $mail \PHPMailer\PHPMailer\PHPMailer */
$mail = app()->resolve('mailer');
$mail->addAddress('john.doe@domain.com');
$mail->Subject = "test";
$mail->Body    = "<b>test body</b>";
$mail->AltBody = "alt body";
$mail->send();

List a directory content with Flysystem service provider and default settings 'local'

$filesystem = app()->resolve('fs_local');
$contents = $filesystem->listContents('', true);
var_dump($contents);

Write and read from session using Session Helper class

// save user info in session
\Jupitern\Slim3\Utils\Session::set('user', ['id' => '1']);
// get user info from session
$user = \Jupitern\Slim3\Utils\Session::get('user');
var_dump($user);

Write and read from cache (using default driver redis)

/** @var \Jupitern\Slim3\Utils\Redis $redis */
$redis = app()->resolve('redis');
$redis->set("key", "some test value");
echo $cache->get("key");