paneric/local

v1.0.5 2022-09-26 09:42 UTC

This package is auto-updated.

Last update: 2024-04-26 13:02:12 UTC


README

Simple local(language) value setter.

Required

  • PHP 7.1+

File structure

  • Local.php
  • local-config.php (an example of required configuration)

Installation

composer

composer require paneric/local:1.0.0

Integration

Slim Framework/PHP-DI example (ver.4)

configuration

Local instance uses generated cookie, own config and application local value (i.e. en, fr, de) to set current language value required in application flow (for example in case of translation integration). It uses base configuration for cookie:

return [
    'name' => 'slim-4-local',
    'default_local' => 'en',
    'expire' => time() + 60 * 60 * 24 * 120, // 120 days
    'path' => '/public',
    'domain' => '127.0.0.1:8080',
    'security' => false,
];

along with simple array as a local mapper with items as follows:

$localMapper = ['en', 'fr', 'de'];

or any other depending on your requirements.

front controller

In this case our practical integration of the local along with Slim 4 framework may look this way:

use Paneric\Local\Local;
use DI\ContainerBuilder;
use Slim\Factory\AppFactory;

define('ENV', 'dev');

define('ROOT_FOLDER', dirname(__DIR__) . '/');
define('APP_FOLDER', ROOT_FOLDER . 'src/');

require ROOT_FOLDER . 'vendor/autoload.php';

try{    
    $definitions = [...];

    $builder = new ContainerBuilder();
    $builder->addDefinitions($definitions);
    $container = $builder->build();

    AppFactory::setContainer($container);
    $app = AppFactory::create();
    
    $language = '...';

    $localConfig = require_once 'local-config.php';
    $localMap = ['en', 'fr', 'de'];
    $local = new Local();
    $local->setValue($localConfig, $localMap, $_COOKIE, $language);

    $container->set('local', $local->getValue());

    // ... (any other require) //

    $app->run();
} catch (Exception $e) {
   echo $e->getMessage();
}

Use cases: In case if your local/language value is established by application middleware or some other functionality triggered within a body of your front controller and it is considered as required for a current request as binding, it should be passed to the local object setMethod() to set a proper cookie useful in the future:

    $language = '...';

    $localConfig = require_once 'local-config.php';
    $localMap = ['en', 'fr', 'de'];
    $local = new Local();
    $local->setValue($localConfig, $localMap, $_COOKIE, $language);

There may happen that language value is set as null or doesn't exist at all. In this case our cookie value is considered as binding if exits otherwise appropriate config value is taken into account. In both cases cookie is set:

    $localConfig = require_once 'local-config.php';
    $localMap = ['en', 'fr', 'de'];
    $local = new Local();
    $local->setValue($localConfig, $localMap, $_COOKIE);