Welcome Guest, Not a member yet? Register   Sign In
How to Access Config File Variables Globally in all Views ?
#1

How to access config file variables Globally in all views without passing it from controller?

i have a config file : app/config/SiteConfig.php
PHP Code:
<?php namespace Config;

use 
CodeIgniter\Config\BaseConfig;

class 
SiteConfig extends BaseConfig
{
    public $siteName  'My Website';
    public $siteDomain  'www.example.com';
    public $siteUrl 'http://www.example.com';
    public $siteSecureUrl 'https://www.example.com';
    public $siteEmail '[email protected]';

    /**
     * Google Site Verification & Maps Key
     */
    public $googleSiteVerificationKey  '';
    public $googleMapsApiKey  '';

    /**
     * Default Meta and Page Title info
     */
    public $defaultPageTitle "";
    public $defaultMetaDesc "";
    public $defaultMetaKeywords "";
    public $defaultRobots "";




 
Now am passing it from controller like this

PHP Code:
<?php 
namespace App\Controllers\Backend;

use 
App\Controllers\Backend;
use 
App\Models\Backend\UserModel;

class 
Users extends Backend
{
    protected $userModel;

    public function __construct(){
    
parent::__construct();
    
$this->userModel = new UserModel();
    }

    /**
     * Function to display users list
     */
    public function index()
    {
    
$data = array(
    
    'siteConfig' => $this->siteConfig
    
);
    
$data['users'] = $this->userModel->getUsers();

    echo 
view'backend/users/list'$data );
    }

    /**
     * Function to create user
     */
    public function createUser()
    {
    
$data = array(
    
  'siteConfig' => $this->siteConfig
    
);
    
$data['groups'] = $this->userModel->getUserGroups();

    echo 
view'backend/users/new'$data );
    }


Is there any better way to accomplish this without passing it from every controller methods?
Reply
#2

Anything you load in BaseController will be available in all the controllers that extend it. There is also the helper function “config()” which not only fetches a config but can use it immediately, e.g.:

<a href=“https://google.com/maps?key=<?= config(‘SiteConfig’)->googleMapsApiKey ?>”>Click</a>
Reply
#3
Thumbs Up 

(11-27-2019, 04:52 AM)MGatner Wrote: Anything you load in BaseController will be available in all the controllers that extend it. There is also the helper function “config()” which not only fetches a config but can use it immediately, e.g.:

<a href=“https://google.com/maps?key=<?= config(‘SiteConfig’)->googleMapsApiKey ?>”>Click</a>

This is exactly what am looking for. Thank You so much.   Smile
Reply
#4

(This post was last modified: 04-07-2020, 06:32 AM by Lauren.)

We must be require to define some global value for application like number of pagination records, user type, site url etc. if you are working with small project then walgreenslistens i will suggest to create global config file for define constants variable.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB