CI 묻고 답하기

제목 전체 페이지에 공통 데이터 전달방법이 있을까요?
카테고리 CI 4 관련
글쓴이 쫑이 작성시각 2023/02/21 12:04:37
댓글 : 2 추천 : 0 스크랩 : 0 조회수 : 7389   RSS

모든 페이지 공통으로 들어가는 템플릿에서 데이터를 불러와야합니다.

현재 각각 컨트롤러 상단에 아래와 같이 데이터를 저장하고 

$this->is_data = $this->member_md->is_data(); 

해당 컨트롤러 함수에서 

$data['is_data'] = $this->is_data;

$this->template->load('lists_v', $data);

이런방법으로 view페이지에 데이터를 전달하고있습니다.

이렇게하니까 모든 컨트롤로 상단에서 데이터를 가져온후 함수에서 다시 가져와서 view페이지로 데이터를 전달해야합니다.

이걸 공통으로 1번에 모든 페이지에 전달하고싶은데 어떻게 해야할지 방법을 모르겠습니다.

class Member extends MY_Controller { }

core 컨트롤러 MY_Controller 여기서 데이터를 모든페이지에 데이터를 전달하는 방법이 있을까요?

 

 다음글 phpoffice 엑셀 업로드 오류건에 대한 질문입니다... (1)
 이전글 controller에러 질문입니다. (2)

댓글

darkninja / 2023/03/04 13:36:47 / 추천 0

한번에 완벽하게 해결되는 방법이 있다면 고민이 좀 덜할텐데요 ㅋ

답변이 될지 모르겠지만

시행착오 끝에 현재는 이렇게 되었습니다.

(지금쯤 해결되어 가고 있겠죠, 많은 분들이 코드 조각들을 공유하면 비교가 가능한데...)

 

BaseController

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;


use CodeIgniter\Services;
use CodeIgniter\Router\Router;

use \App\Libraries\Tank_auth;
use \App\Libraries\xLogger;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 */
abstract class BaseController extends Controller
{
	/**
	 *
	 * @var array
	 */
	public $data = [];
    public $authdata = [];

    /**
     * Instance of the main Request object.
     *
     * @var CLIRequest|IncomingRequest
     */
    protected $request;

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = [];

    protected $db;
    protected $routes;
    protected $router;
    protected $uri;

    protected $controllerName;
    
    protected $TotalSegments;
	protected $seg_controller;
    protected $seg_func;
    protected $seg_table;
	protected $seg_index;
    
	protected $session;
    protected $security;
    protected $lang;

    protected $xlogger;
	
    /**
     * Constructor.
     */
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
		// Do Not Edit This Line
		parent::initController($request, $response, $logger);

		// Preload any models, libraries, etc, here.
		// E.g.: $this->session = \Config\Services::session();

		date_default_timezone_set('Asia/Seoul');

		helper('ci');
        register_ci_instance($this);

		$this->session = \Config\Services::session();
		$this->db = \Config\Database::connect();
		$this->security = \Config\Services::security();
		$this->lang = \Config\Services::language();

        $this->xlogger = new xLogger();
		$this->xlogger->initialize(["log_dir" => DOC_BASE.LOGGER_PATH]);
        //$this->xlogger->write_log = false;
        //$this->xlogger->print_log = false;
        //$this->xlogger->log_level = "debug";

		helper('form');
		helper('session');
		helper('url');

        helper('my_alert');
		helper('my_array');
        helper('my_url');
        helper('my_util');
		helper('my_weather');
		
		weather_folder_check();

		// Create a new instance of our RouteCollection class.
		//$this->routes = \Config\Services::routes();
		//$this->router = new Router($this->routes);
		$this->router = service('router');

		//controller class 이름
		$this->controllerName = class_basename($this->router->controllerName());
		//My_Controller 를 상속받은 class 이름
		//echo $this->controllerName;
		//$method = $router->methodName();

		$this->request = \Config\Services::request();
		$this->uri = $this->request->uri;
		$this->TotalSegments = $this->uri->getTotalSegments();

		//echo $uri->getScheme();         // http
		//echo $uri->getAuthority();      // snoopy:password@example.com:88
		//echo $uri->getUserInfo();       // snoopy:password
		//echo $uri->getHost();           // example.com
		//echo $uri->getPort();           // 88
		//echo $uri->getPath();           // /path/to/page
		//echo $uri->getQuery();          // foo=bar&bar=baz
		//echo $uri->getSegments();       // ['path', 'to', 'page']
		//echo $uri->getSegment(1);       // 'path'
		//echo $uri->getTotalSegments();  // 3

		$this->seg_controller = $this->uri->getTotalSegments()>=1 ? $this->uri->getSegment(1) : '/';
		$this->seg_func       = $this->uri->getTotalSegments()>=2 ? $this->uri->getSegment(2) : '';
		$this->seg_table      = $this->uri->getTotalSegments()>=3 ? $this->uri->getSegment(3) : '';
		$this->seg_index      = $this->uri->getTotalSegments()>=4 ? $this->uri->getSegment(4) : '';

		$this->controller_setting_model = new \App\Models\controller_setting_model();
		$this->iclw_setting_model = new \App\Models\iclw_setting_model();

		$this->nestedset_model = new \App\Models\nestedset_model();
		$this->board_category_model = new \App\Models\board_category_model();
		
		$this->board_tag_model = new \App\Models\board_tag_model();

		$this->authdata['isloggedIn'] = FALSE;
		$this->authdata['user_id'] = '';
		$this->authdata['user_name'] = '';
	  
		$this->ionAuthLib = new \App\Libraries\IonAuthLib();
		if ($this->ionAuthLib->loggedIn()) {
			$this->authdata['isloggedIn'] = TRUE;
			$this->authdata['user_id'] = $this->session->get('user_id');
			$this->authdata['user_name'] = $this->session->get('user_name');
		}

		$iclw_arr = array('css'=>array(), 'php_include'=>array(), 'js'=>array(), 'js_include'=>array(), 'js_path'=>array(), 'js_tail'=>array());

		//controller에 따라 화면을 다르게 구성
		//iclw_list에 화면에 표시할 목록지정

		//default setting 읽기
		$controller_setting_table = CONTROLLER_SETTING;
		$cm = $this->controller_setting_model->get(ICLW_CONTROLLER_DEFAULT);

		if (isset($cm) && $cm) {
			//default setting
			//controller_list에서 controller 이름이 포함되어 있을때만 적용되어
			//지정된 위치(left, center, right)에 표시됨 (active : yes)

			//echo "<xmp>";
			//var_dump($cm->controller_list);
			//echo "</xmp>";
			//echo $this->controllerName;
			//echo class_basename(service('router')->controllerName()); // Mycontroller

			$pos = strpos($cm->controller_list, $this->controllerName);
			if ($pos!==false) {
				$iclw_list = string2KeyedArray($cm->iclw_list);
				//배열 덮어쓰기
				$iclw_arr = array_replace_recursive($iclw_arr, $this->iclw_setting_model->get_iclw_arr($iclw_list));
			}
		}

		//controller setting 읽기
		//이 값이 없으면 default setting 값이 사용됨
		$cm = $this->controller_setting_model->get($controller_setting_table, $this->controllerName);
		if (isset($cm) && $cm) {
			$iclw_list = string2KeyedArray($cm->iclw_list);
			//배열 덮어쓰기
			$iclw_arr = array_replace_recursive($iclw_arr, $this->iclw_setting_model->get_iclw_arr($iclw_list));
		}	

		if ($iclw_arr) {
			//compare_rank 값으로 정렬, 적재되는 순서를 정함
			uasort($iclw_arr['css'], 'compare_rank');
			uasort($iclw_arr['js'], 'compare_rank');
			uasort($iclw_arr['js_include'], 'compare_rank');
			uasort($iclw_arr['js_path'], 'compare_rank');
			//top, left 따로따로
			foreach ($iclw_arr['php_include'] as $php) {
				uasort($php, 'compare_rank');
			}
		}

		//echo "<xmp>";
		//var_dump($iclw_arr['css']);
		//var_dump($iclw_arr['php_include']);
		//var_dump($iclw_arr['js']);
		//echo "</xmp>";

		$ztree_json = $this->board_category_model->get_JSONztree("name");
		$tree_json = $this->board_category_model->get_JSON("text");

		$this->data = Array(
			'head_data' => Array(
				'title' => 'main',
				'session' => $this->session,
				'isloggedIn' => $this->authdata['isloggedIn'],
				'user_id' => $this->authdata['user_id'],
				'user_name' => $this->authdata['user_name'],
				'tagcloud' => $this->board_tag_model->get_ahref(),
				'uri' => $this->uri,
				'TotalSegments' => $this->TotalSegments,
				'seg_controller' => $this->seg_controller,
				'seg_func' => $this->seg_func,
				'seg_table' => $this->seg_table,
				'seg_index' => $this->seg_index,
				'xlogger' => $this->xlogger,
				'css' => $iclw_arr['css'],
				'php_include' => $iclw_arr['php_include'],
			),
			'view_data' => Array(
				'session' => $this->session,
				'isloggedIn' => $this->authdata['isloggedIn'],
				'user_id' => $this->authdata['user_id'],
				'user_name' => $this->authdata['user_name'],
				'uri' => $this->uri,
				'TotalSegments' => $this->TotalSegments,
				'seg_controller' => $this->seg_controller,
				'seg_func' => $this->seg_func,
				'seg_table' => $this->seg_table,
				'seg_index' => $this->seg_index,
				'xlogger' => $this->xlogger,
				'php_include' => $iclw_arr['php_include'],
			),
			'tail_data' => Array(
				'session' => $this->session,
				'isloggedIn' => $this->authdata['isloggedIn'],
				'user_id' => $this->authdata['user_id'],
				'user_name' => $this->authdata['user_name'],
				'ztree_json' => $ztree_json,
				'tree_json' => $tree_json,
				'TotalSegments' => $this->TotalSegments,
				'seg_controller' => $this->seg_controller,
				'seg_func' => $this->seg_func,
				'seg_table' => $this->seg_table,
				'xlogger' => $this->xlogger,
				'php_include' => $iclw_arr['php_include'],
				'js' => $iclw_arr['js'],
				'js_include' => $iclw_arr['js_include'],
			),
		);

		//echo "<xmp>";
		//var_dump($ztree1_json);
		//echo "</xmp>";
		//$ztree1_json = 
		//string(2463) " [ { "id" : "1", "name" : "", "controller_name" : "/", "url" : "/ci-426/public/", "lft" : "1", "rgt" : "32", "parent_id" : "0", "children" : [ { "id" : "5", "name" : "farm", "controller_name" : "/board", "url" : "/ci-426/public/board/index/farm", "lft" : "2", "rgt" : "3", "parent_id" : "1", "children" : [ ] }, { "id" : "3", "name" : "controller setting", "controller_name" : "/controller_setting", "url" : "/ci-426/public/controller_setting", "lft" : "4", "rgt" : "5", "parent_id" : "1", "children" : [ ] }, { "id" : "9", "name" : "iclw_setting", "controller_name" : "/iclw_setting", "url" : "/ci-426/public/iclw_setting", "lft" : "6", "rgt" : "7", "parent_id" : "1", "children" : [ ] }, { "id" : "2", "name" : "category", "controller_name" : "/board_category", "url" : "/ci-426/public/board_category", "lft" : "8", "rgt" : "9", "parent_id" : "1", "children" : [ ] }, { "id" : "8", "name" : "file", "controller_name" : "/board_file", "url" : "/ci-426/public/board_file", "lft" : "10", "rgt" : "11", "parent_id" : "1", "children" : [ ] }, { "id" : "15", "name" : "gam", "controller_name" : "/board", "url" : "/ci-426/public/board/index/gam", "lft" : "12", "rgt" : "13", "parent_id" : "1", "children" : [ ] }, { "id" : "7", "name" : "search", "controller_name" : "/search", "url" : "/ci-426/public", "lft" : "14", "rgt" : "15", "parent_id" : "1", "children" : [ ] }, { "id" : "4", "name" : "tag", "controller_name" : "/board_tag", "url" : "/ci-426/public/board_tag", "lft" : "16", "rgt" : "17", "parent_id" : "1", "children" : [ ] }, { "id" : "18", "name" : "weather", "controller_name" : "/weather", "url" : "/ci-426/public/weather", "lft" : "18", "rgt" : "19", "parent_id" : "1", "children" : [ ] }, { "id" : "10", "name" : "farm", "controller_name" : "", "url" : "/ci-426/public", "lft" : "20", "rgt" : "31", "parent_id" : "1", "children" : [ { "id" : "11", "name" : "논농사", "controller_name" : "", "url" : "/ci-426/public", "lft" : "21", "rgt" : "26", "parent_id" : "10", "children" : [ { "id" : "13", "name" : "감자", "controller_name" : "", "url" : "/ci-426/public", "lft" : "22", "rgt" : "23", "parent_id" : "11", "children" : [ ] }] }] }] }, { "id" : "12", "name" : "밭농사", "controller_name" : "", "url" : "/ci-426/public", "lft" : "27", "rgt" : "30", "parent_id" : "10", "children" : [ { "id" : "14", "name" : "단감", "controller_name" : "", "url" : "/ci-426/public", "lft" : "28", "rgt" : "29", "parent_id" : "12", "children" : [ ] }] } ] "

		//foreach ($this->data['head_data']['css'] as $key => $value) {
		//  echo $value['css'].'.css<br >';
		//}
		//foreach ($this->data['tail_data']['js'] as $key => $value) {
		//  echo $value['js'].'.js<br >';
		//}
    }

    public function satimg() 
	{
		$satimg = get_satimg(true);

		if ($satimg) {
			$imgret = array();
			$imgret['imgsrc'] = end($satimg)[0];
			$imgret['title'] = end($satimg)[1];
			return json_encode($imgret);
		}
		else
			return json_encode(false);
    }
	
    public function typimg() 
	{
		$typimg = get_typimg(true);

		if ($typimg) 
			return json_encode($typimg);
		else
			return json_encode(false);
    }

	public function weatherhtml() 
	{
		$wHTML = ''; 

        $weather = get_weather();
		if ($weather) {
			foreach ($weather as $w) {  
				$wHTML .= '<p><img src="'.$w['wfPng'].'" title="'.$w['day'].$w['hour']." ".$w['temp'].'"></img></p>';
			}	
			if ($this->session->has('pubDate'))
				$this->session->remove('pubDate');
			$this->session->set('pubDate', $weather[0]['pubDate']);
		}
		else
			$this->session->set('pubDate', '');

		return $wHTML;
	}
	
}

 

Board Controller

<?php namespace App\Controllers;

if (!defined('BASEPATH')) exit('No direct script access allowed');

use App\Libraries\My_Upload;
use App\Libraries\MY_Pagination;
use App\Libraries\My_Htmlpurifier;

class Board extends BaseController {

    var $board_controller        = BOARD_CONTROLLER;
    var $board_skin              = BOARD_SKIN;
    var $board_replymode         = BOARD_REPLYMODE;
    var $board_comment_replymode = BOARD_COMMENT_REPLYMODE;

    var $cut_contents            = CUT_CONTENTS;

    var $per_page                = PER_PAGE;
    var $per_page_list           = PER_PAGE_LIST;

    var $per_page_comment        = PER_PAGE_COMMENT;
    var $per_page_comment_list   = PER_PAGE_COMMENT_LIST;

    var $validation;

    protected $request;

    protected $isloggedIn;

	public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
	{
		// Do Not Edit This Line
		parent::initController($request, $response, $logger);

        $this->isloggedIn = $this->authdata['isloggedIn'];

        $this->validation = \Config\Services::validation();

        $this->board_model = new \App\Models\board_model();
        $this->board_comment_model = new \App\Models\board_comment_model();
        $this->board_file_model = new \App\Models\board_file_model();

		$this->file_pattern = "/<a[^>]*href=[\"']?([^>\"']+)[\"']?[^>]*>/i";
        $this->img_pattern  = "/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i";

		//$this->file_pattern = "/<a[^>]*href=[\"']?(\.(png|gif|jpg|jpeg|bmp|rar|zip|7zip|mp3|mp4|mov|flv|wmv|swf|avi)+[^>\"']+)[\"']?[^>]*>/i";
        //$this->img_pattern2  = "/<img[^>]*src=[\"'](?=\/)[repositary]?([^>\"']+)[\"']?[^>]*>/i";
        //$this->img_pattern22 = "/<img[^>]*src=[\"'](\/repositary?([^>\"']+))[\"']?[^>]*>/i";

        $this->root_path = ROOT_PATH;

        $this->http_root = HTTP_ROOT;
        $this->doc_root = DOC_ROOT;
        
		$this->http_base = HTTP_BASE;
        $this->doc_base = DOC_BASE;

        $this->base_path = BASE_PATH;

        $this->upload_path = UPLOAD_PATH;
        $this->image_path = IMAGE_PATH;
        $this->file_path = FILE_PATH;
        $this->temp_path = TEMP_PATH;

        $this->temp_file_name = '';
        $this->temp_file_ext = '';

        $data = Array(
            'head_data' => Array(
                'title' => 'Board',
                'css' => array(
                    'pagination' => Array(
                        'css' => '/pagination',
                        //'css' => ROOT_PATH.CSS_PATH.'/pagination',
                    ),
                ),
            ),
            'view_data' => Array(
                'board_controller' => $this->board_controller,
                'board_replymode' => $this->board_replymode,
            ),
      		'tail_data' => Array(
      		),
        );
        $this->data = array_replace_recursive($this->data, $data);
    }

    // render_page
    public function render_page($view, $data) 
	{
        $view = $this->board_controller .'/'. $this->board_skin .'/'. $view;
        $data = array_replace_recursive($this->data, $data);

        echo view('main_head', $data['head_data']);
        echo view($view, $data['view_data']);
        echo view('main_tail', $data['tail_data']);
    }

    // show a list of board
    public function index($board_table=BOARD, $page_index=1, $order='modify_date', $asc='desc') 
    {
		$per_page = $this->per_page;
    	$total_rows = 0;
    	$boards = $this->board_model->paginated_reply($board_table, $page_index, $per_page, $total_rows, $order, $asc);
        $redirect_url = $this->board_controller.'/index/'.$board_table;
        $base_url = ROOT_PATH.'/'.$redirect_url;

    	//$template_name = 'default_full';
    	//$uri_segment = 6;
    	//$group = 'default';
    	//$pager = service('pager');
    	//$pager->setPath($base_url, $group); // Additionally you could define path for every group.
    	//$pageLinks = $pager->makeLinks($page_index, $per_page, $total_rows, $template_name, $uri_segment, $group);    

        $MyPager = new MY_Pagination();
		$page_config = array();
		$page_config['base_url'] = $base_url;
		$page_config['per_page'] = $per_page;
		$page_config['total_rows'] = $total_rows;
		$page_config['uri_segment'] = 4;
		$MyPager->initialize($page_config);
        $pageLinks = $MyPager->create_links();

    	$t = intval(($total_rows-1) / $per_page) + 1;
    	if ($page_index > $t) {
      	    $this->response->redirect(site_url($redirect_url.'/'.$t));
	    }

    	$data = Array(
      		'head_data' => Array(
        		'title' => 'Board list',
      		),
    	  	'view_data' => Array(
	        	'boards' => $boards,
		        'pageLinks' => $pageLinks,
    		    'cut_contents' => $this->cut_contents,
        		'board_table' => $board_table,
	        	'comment_table' => $board_table.COMMENT,
    		    'page_index' => $page_index,
		        'db' => $this->db,
    		    'board_table' => $board_table,
        		'board_model' => $this->board_model,
      		),
	    );

    	$this->render_page('index', $data);
  	}

 

darkninja / 2023/03/05 11:19:14 / 추천 0

view에 넘기는 변수에 로그인 정보가 포함되는데

BaseController에서 상속받은 Controller가 로그인 정보를 덮어쓰면 심각한 문제가

발생하겠네요

저는 로컬에서 혼자 사용하는 거라 구현하기에도 급급한 형편이라서.

 

로그인 정보를 protected변수로 바꾼다고 해도

여전히 위험이 남아 있겠네요.