PHP code example of simsoft / slim

1. Go to this page and download the library: Download simsoft/slim library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

simsoft / slim example snippets



declare(strict_types=1);
lim\App;
use function Simsoft\Slim\response;

Route::make()
    ->withErrorHandler(false, true, true)
    ->withRouting(function(App $app) {
        // Define a GET route for the homepage
        $app->get('/', function() {
            response('Hello World!');
        });

        // {name} is a URL parameter — passed as a function argument
        $app->get('/{name}', function(string $name) {
            response("Hello $name!");
        });
    })
    ->run();

Route::make($container)                      // Optional PSR-11 dependency injection container
    ->withDomain('https://example.com')      // Your app's domain (for URL generation)
    ->withBasePath('/api/v1')                // Prefix all routes with this path
    ->withErrorHandler(...)                  // Configure error display and logging
    ->withMiddleware(function(App $app) { }) // Register global middleware
    ->withRouting(
        routes: function(App $app) { },      // Define your routes here
        cachePath: '/path/to/routes.cache',  // Optional: cache routes for production
    )
    ->run();                                 // Process the request and send a response


namespace App;

use function Simsoft\Slim\response;

class UserController
{
    public function index() { response('Users list'); }

    public function show(string $id) { response("User $id"); }

    // Returning a string sends it as text
    public function version(): string { return '1.0.0'; }

    // Returning an array sends it as JSON automatically
    public function list(): array { return ['users' => []]; }
}

Route::make()
    ->withRouting(function(App $app) {
        $app->get('/users', [UserController::class, 'index']);
        $app->get('/users/{id}', [UserController::class, 'show']);
    })
    ->run();

use Simsoft\Slim\Traits\ContainerAwareTrait;

/**
 * @property \App\Services\Logger $logger
 * @property \App\Services\Database $db
 */
class UserController
{
    use ContainerAwareTrait;

    public function index()
    {
        $this->logger->info('accessed');  // Resolves $container->get('logger')
        $users = $this->db->fetchAll('users');
        response($users);
    }
}

use function Simsoft\Slim\request;
use function Simsoft\Slim\response;

// Reading the request
request()->getQueryParams();           // Get URL query parameters (?key=value)
request()->getParsedBody();            // Get POST body data
request()->isMethod('post');           // Check HTTP method
request()->isXHR();                    // Detect AJAX requests
request()->getBearerToken();           // Extract "Bearer xxx" token ('' if absent/not Bearer)
request()->urlFor('users.show', ['id' => '1']); // Generate URL from route name
request()->notFound();                 // Throw exception 404

// Sending responses
response('Hello World');               // Plain text
response(['status' => 'ok']);          // JSON (arrays auto-encode)
response('Error', 500);               // Text with status code
response()->json($data);              // Explicit JSON
response()->xml($xmlString);          // XML with the correct content-type
response()->redirect('/path', 301);   // Redirect
response()->header('X-Custom', 'val'); // Set response header

use Simsoft\Slim\URL;

URL::for('users.show', ['id' => '42']);       // /users/42
URL::fullFor('users.show', ['id' => '42']);   // https://example.com/users/42

use Simsoft\Slim\Middlewares\Auth;
use Simsoft\Slim\Middlewares\CORS;
use Simsoft\Slim\Middlewares\CacheOff;
use Simsoft\Slim\Middlewares\RateLimit;
use Simsoft\Slim\Middlewares\Csrf;
use Simsoft\Slim\Middlewares\SecurityHeaders;

Route::make()
    ->withMiddleware(function(App $app) {
        $app->add(new SecurityHeaders());                // Security headers
        $app->add(new CORS('https://myapp.com'));        // Allow cross-origin requests
        $app->add(new CacheOff());                       // Prevent browser caching
        $app->add(new RateLimit(maxRequests: 100, windowSeconds: 60)); // 100 req/min
        $app->add(new Csrf());                           // Protect forms from CSRF attacks
        $app->add(new Auth(fn($request) => $_SESSION['user'] ?? null)); // Require login
    })
    ->withRouting(function(App $app) { /* ... */ })
    ->run();

Route::make()
    ->withErrorHandler(
        displayError: false,          // true in dev, false in production
        logError: true,               // Write errors to log
        logErrorDetails: true,        // Include stack traces
        errorHandlerClass: CustomErrorHandler::class, // Optional custom handler
    )
    ->withRouting(function(App $app) { /* ... */ })
    ->run();