Skip to content

Commit

Permalink
Merge pull request #18 from adrianfalleiro/slim-4
Browse files Browse the repository at this point in the history
Refactor for Slim 4
  • Loading branch information
adrianfalleiro authored Jun 27, 2020
2 parents ce64244 + e1bfa34 commit 5eef549
Show file tree
Hide file tree
Showing 57 changed files with 4,231 additions and 386 deletions.
82 changes: 33 additions & 49 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,93 +7,77 @@ Create and run command line tasks for the Slim PHP micro-framework
**Installation**

```
composer require adrianfalleiro/slim-cli-runner ^2.6
composer require adrianfalleiro/slim-cli-runner ^3.0
```

*For Slim 3 support install version 2.6 or lower*

**Register Middleware**

Register the middleware in `middleware.php`

```php
$app->add(\adrianfalleiro\SlimCLIRunner::class);
$app->add(new adrianfalleiro\SlimCliRunner\CliRunner::class);
```

## Define, Register and run your tasks

**Task definition**

Tasks are simply classes which have a public `command()` method.
Tasks are classes which extend `CliAction` and have a public `command()` method.

The dependency container is passed to the constructor, and console arguments are passed to the `command()` method.
You can inject dependencies through the class constructor.

```php
use \Psr\Container\ContainerInterface;
use \RuntimeException;

class SampleTask {
use Psr\Http\Message\ResponseInterface as Response;
use adrianfalleiro\SlimCliRunner\CliAction;

/** @var ContainerInterface */
protected $container;
use Psr\Log\LoggerInterface;

/**
* Constructor
*
* @param ContainerInterface $container
* @return void
*/
public function __construct($container)
class ExampleCliAction extends CliAction
{
public function __construct(LoggerInterface $logger)
{
// access container classes
// eg $container->get('redis');
$this->container = $container;
$this->logger = $logger;
}

/**
* SampleTask command
*
* @param array $args
* @return void
*/
public function command($args)
protected function action(): Response
{
// Access items in container
$settings = $this->container->get('settings');

// Throw if no arguments provided
if (empty($args)) {
throw new RuntimeException("No arguments passed to command");
}

$firstArg = $args[0];
$arg0 = $this->resolveArg(0);
$this->logToConsole("arg 0 is {$arg0}");

// Output the first argument
return $firstArg;
return $this->respond();
}
}
```

**Tasks registration**

Add a new key in your `settings.php` file called `commands` and list your tasks.
_Keep in mind that you should NOT add this within the 'settings' values_
Add a new key in your `settings.php` definitions file called `commands` and list your tasks.
To define a default task (For use when no command name is provided) add a new task with `__default` as key

```php
'settings' => [
// ...
],
'commands' => [
'SampleTask' => \Namespace\To\Task::class
],
return function (ContainerBuilder $containerBuilder) {
// Global Settings Object
$containerBuilder->addDefinitions([
'settings' => [
...
],
'commands' => [
'__default' => \Namespace\To\Task::class
'SampleTask' => \Namespace\To\Task::class
]
]);
};
```

**Run Tasks**

There are multiple ways of doing this:
Directly via commandline:
Directly via command line:

```
php /path/to/slim/public/index.php SampleTask argument1 argument2 argument3
php public/index.php SampleTask arg1 arg2 arg3
```

Via composer:
Expand All @@ -120,4 +104,4 @@ composer cli SampleTask argument1 argument2 argument3

## Examples

Examples can be found in the `examples/` folder
An example project can be found in the `examples/` folder
12 changes: 8 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,25 @@
}
],
"require": {
"php": ">=5.5.0",
"psr/container": "^1.0"
"php": ">=7.1",
"slim/psr7": "^0.6.0",
"psr/http-message": "^1.0",
"psr/http-server-middleware": "^1.0",
"php-di/php-di": "^6.0"
},
"require-dev": {
"squizlabs/php_codesniffer": "^2.5"
},
"autoload": {
"psr-4": {
"adrianfalleiro\\": "src/"
"adrianfalleiro\\SlimCliRunner\\": "src/"
}
},
"scripts": {
"test": [
"@phpcs"
],
"phpcs": "php vendor/bin/phpcs"
"phpcs": "php vendor/bin/phpcs",
"phpcbf": "php vendor/bin/phpcbf"
}
}
1 change: 1 addition & 0 deletions examples/ExampleApp/.coveralls.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
json_path: coveralls-upload.json
5 changes: 5 additions & 0 deletions examples/ExampleApp/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.idea/
/coverage/
/vendor/
/logs/*
!/logs/README.md
24 changes: 24 additions & 0 deletions examples/ExampleApp/.travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
language: php

dist: trusty

matrix:
include:
- php: 7.1
- php: 7.2
- php: 7.3
env: ANALYSIS='true'
- php: nightly

allow_failures:
- php: nightly

before_script:
- composer require php-coveralls/php-coveralls:^2.1.0
- composer install -n

script:
- if [[ "$ANALYSIS" == 'true' ]]; then vendor/bin/phpunit --coverage-clover clover.xml ; fi

after_success:
- if [[ "$ANALYSIS" == 'true' ]]; then vendor/bin/php-coveralls --coverage_clover=clover.xml -v ; fi
14 changes: 14 additions & 0 deletions examples/ExampleApp/CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# How to Contribute

## Pull Requests

1. Fork the Slim Skeleton repository
2. Create a new branch for each feature or improvement
3. Send a pull request from each feature branch to the **4.x** branch

It is very important to separate new features or improvements into separate feature branches, and to send a
pull request for each branch. This allows us to review and pull in new features or improvements individually.

## Style Guide

All pull requests must adhere to the [PSR-2 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md).
42 changes: 42 additions & 0 deletions examples/ExampleApp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Slim Framework 4 Skeleton Application

[![Coverage Status](https://coveralls.io/repos/github/slimphp/Slim-Skeleton/badge.svg?branch=master)](https://coveralls.io/github/slimphp/Slim-Skeleton?branch=master)

Use this skeleton application to quickly setup and start working on a new Slim Framework 4 application. This application uses the latest Slim 4 with Slim PSR-7 implementation and PHP-DI container implementation. It also uses the Monolog logger.

This skeleton application was built for Composer. This makes setting up a new Slim Framework application quick and easy.

## Install the Application

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

```bash
composer create-project slim/slim-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 `logs/` is web writable.

To run the application in development, you can run these commands

```bash
cd [my-app-name]
composer start
```

Or you can use `docker-compose` to run the app with `docker`, so you can run these commands:
```bash
cd [my-app-name]
docker-compose up -d
```
After that, open `http://localhost:8080` in your browser.

Run this command in the application directory to run the test suite

```bash
composer test
```

That's it! Now go build something cool.
28 changes: 28 additions & 0 deletions examples/ExampleApp/app/dependencies.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);

use DI\ContainerBuilder;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\UidProcessor;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
LoggerInterface::class => function (ContainerInterface $c) {
$settings = $c->get('settings');

$loggerSettings = $settings['logger'];
$logger = new Logger($loggerSettings['name']);

$processor = new UidProcessor();
$logger->pushProcessor($processor);

$handler = new StreamHandler($loggerSettings['path'], $loggerSettings['level']);
$logger->pushHandler($handler);

return $logger;
},
]);
};
12 changes: 12 additions & 0 deletions examples/ExampleApp/app/middleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);

use App\Application\Middleware\SessionMiddleware;
use Slim\App;

use adrianfalleiro\SlimCliRunner\CliRunner;

return function (App $app) {
$app->add(SessionMiddleware::class);
$app->add(CliRunner::class);
};
13 changes: 13 additions & 0 deletions examples/ExampleApp/app/repositories.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);

use App\Domain\User\UserRepository;
use App\Infrastructure\Persistence\User\InMemoryUserRepository;
use DI\ContainerBuilder;

return function (ContainerBuilder $containerBuilder) {
// Here we map our UserRepository interface to its in memory implementation
$containerBuilder->addDefinitions([
UserRepository::class => \DI\autowire(InMemoryUserRepository::class),
]);
};
21 changes: 21 additions & 0 deletions examples/ExampleApp/app/routes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);

use App\Application\Actions\User\ListUsersAction;
use App\Application\Actions\User\ViewUserAction;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
use Slim\Interfaces\RouteCollectorProxyInterface as Group;

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

$app->group('/users', function (Group $group) {
$group->get('', ListUsersAction::class);
$group->get('/{id}', ViewUserAction::class);
});
};
23 changes: 23 additions & 0 deletions examples/ExampleApp/app/settings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);

use DI\ContainerBuilder;
use Monolog\Logger;

return function (ContainerBuilder $containerBuilder) {
// Global Settings Object
$containerBuilder->addDefinitions([
'settings' => [
'displayErrorDetails' => true, // Should be set to false in production
'logger' => [
'name' => 'slim-app',
'path' => isset($_ENV['docker']) ? 'php://stdout' : __DIR__ . '/../logs/app.log',
'level' => Logger::DEBUG,
],
],
'commands' => [
'Example' => \App\Application\Actions\Cli\ExampleCliAction::class,
'ExampleWithoutConstructor' => \App\Application\Actions\Cli\ExampleWithoutConstructorCliAction::class
]
]);
};
Loading

0 comments on commit 5eef549

Please sign in to comment.