We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Phalcon GetText Adapter as a service - how to get locale from session

Hi All! I have a problem with setting up Phalcon Incubator Gettext Adapter in a service container.

I want to set locale from session. I have sth like this:


<?php

$di = new Phalcon\DI\FactoryDefault();

$di->setShared('session', function () {
    $session = new Phalcon\Session\Adapter\Files();
    $session->start();
    return $session;
});

$di->set('t', function () {

    //here is my problem

    if(isset($_SESSION["locale"])){
        $locale = $_SESSION["locale"];
    }
    else {
        $locale = 'cz_CZ';
    }

    $t = new Phalcon\Translate\Adapter\Gettext(array(
        'locale' => $locale,
        'file' => 'messages',
        'directory' => '../app/locale'
    ));

    return $t;
},true);

but it doesn't work. I think the problem is that at the moment when I implement Gettext there is no session started yet. But I don't know how to solve it.

Thanks!



51.2k

Try to this:

$di->set('t', function () use($di) {

    if ($di->session->has('locale')) {
        $locale = $di->session->get('locale');
    }else {
        $locale = 'cz_CZ';
    }

    $t = new Phalcon\Translate\Adapter\Gettext(array(
        'locale' => $locale,
        'file' => 'messages',
        'directory' => '../app/locale'
    ));

    return $t;
},true);


26.3k

Unfortunetly I does not work. I am getting a blank page...



51.2k

Well, any logs from your webserver ?



51.2k
Accepted
answer

Also try to replace

$di->session

with

$di->getShared('session')


26.3k
edited Apr '14

Now it works! Huge thanks Calin Rada! ;)



26.3k

It started to wrok after I replaced


$di->session

with


$di->getShared('session')

Thanks again, it halped me a lot! ;) Lot of f k's resounded around my room for a few hours... :)