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

Use Config information in components

I have in the config file this lines

    'application' => [
        'appDir'         => APP_PATH . '/',
        'controllersDir' => APP_PATH . '/controllers/',
        'modelsDir'      => APP_PATH . '/models/',
        'migrationsDir'  => APP_PATH . '/migrations/',
        'viewsDir'       => APP_PATH . '/views/',
        'pluginsDir'     => APP_PATH . '/plugins/',
        'libraryDir'     => APP_PATH . '/library/',
        'logsDir'        => BASE_PATH . '/logs/',
        'cacheDir'       => BASE_PATH . '/cache/',
    public function LogErro( $dData, $sHora, $sMetodo, $sLog )
    {
        try
        {

            $sPasta = __DIR__ .'../../../logs'; --> i am using this now, but i want use the applicattion  configuration, to make configurable

            // Apagamos o cache do php
            clearstatcache();

            // Se não existe a pasta log a criamos como 777
            if ( !file_exists( $sPasta  ) )
            {
                if ( !mkdir( $sPasta, 0777 ) )
                {
                    $aErro = error_get_last();
                    throw new \Exception( $aErro['message'], 7000 );
                }
            }
            file_put_contents( $sPasta . '/' . $sMetodo . '_'. $dData .'_' . str_replace( ':', '_', $sHora )  . '_ERRO.log', $sLog );
        } catch( \Exception $e ) {
            // Gravo erro de execução do log
            file_put_contents( $sPasta . '/erro_base_' . $sMetodo . '_'. $dData .'_' . str_replace( ':', '_', $sHora )  . '_ERRO.log', $e->getCode() . ' ==> ' . $e->getMessage());
        }
    }

I want to use the 'logsDir' inside my component, to save logs with especific format.

How i reference the aplicattion or reference the DI inside the component ?



4.5k
edited Aug '18

A component extends the class 'Phalcon\Di\Injectable' so it should be aware to access your di.

Use any of those below at the top of your function:

$config =$this->di->getConfig();
$config =$this->di->getShared('config');

$config =$this->getDI()->getConfig();                      <- my preferred way
$config =$this->getDI()->getShared('config');

or

$di = \Phalcon\DI::getDefault();
$config =$di->getConfig();

And then in your code

$config->application->logsDir to get the logdir from your config file



1.4k
Accepted
answer

thank you Work fine

            $config =$this->getDI()->getShared('config');
            //$sPasta = __DIR__ .'../../../logs';
            $sPasta =  $config->path ("application.logsDir", '' );

            // Apagamos o cache do php
            clearstatcache();

Problem solved!!!

edited Aug '18

@amichelins you should have accepted @Hoet 's answer, instead of yours.