CodeIgniter Forums
Codeigniter 4: Get value from BaseController to custom helper - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Codeigniter 4: Get value from BaseController to custom helper (/showthread.php?tid=77929)



Codeigniter 4: Get value from BaseController to custom helper - Hemil Sarker - 11-05-2020

Seems get_instance() is no longer working in Codeigniter 4. But I need to get some value from BaseController to my custom_helper. Here is my code snippet:
BaseController.php
Code:
<?php namespace App\Controllers;
class BaseController extends Controller
{
protected $helpers = ['custom'];
public function initController(...) {
  parent::initController(...);

  $myconfig = config('MyConfig');
  $this->languages = $myconfig->languages;
  $this->selected_lang = $myconfig->site_lang;
  $lang_segment = $this->request->uri->getSegment(1);
  foreach ($this->languages as $lang) {
    if ($lang_segment == $lang->short_form) {
      $this->selected_lang = $lang;
      $this->lang_base_url = base_url() . $lang->short_form . "/";
    }
  }
}
}
// Here I need to pass ($this->selected_lang) value to my custom_helper.

custom_helper.php
Code:
<?php
if (!function_exists('trans')) {
    function trans($string)
    {
        $language_translations = get_translation_array($this->selected_lang->id);
        // --> Here I want to get ($this->selected_lang->id) value from BaseController.
       
        if (!empty($language_translations[$string])) {
            return $language_translations[$string];
        }
        return "";
    }
}
function get_translation_array($land_id)
{
    .......
}

I'm not sure is it possible or not! I'm newbie in CI4. Please suggest if is there any solutions. Thanks in advance.


RE: Codeigniter 4: Get value from BaseController to custom helper - InsiteFX - 11-05-2020

Pass it from the BaseController to your helper using sessions.