如何使此代码在不同的视图上可重用?正确的方法 [英] How do I make this code reusable on different views? Proper method

查看:70
本文介绍了如何使此代码在不同的视图上可重用?正确的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于执行以下操作的正确方法,我有些困惑.这是一个类的功能还是对象? (不确定)所以这里(请客气)我正在同时学习codeigniter/php.

    $is_live = $this->session->userdata('email');
    $is_live = ucwords($is_live);
            if (!$is_live == null)
                   echo 'Hello, '.$is_live.
                   ' <b>(Not you? '.'<a href="' .base_url().
                   'main/logout">Log Out</a>) </b>'; 

我编写了这段代码,该代码检查是否设置了会话以及是否设置为true来回显详细信息.我目前在view/main上有此代码,但是我想在所有页面上显示此代码.

执行此操作的正确方法是什么?

  1. 我是否创建一个自动在每个页面上加载的view/header并在其中插入code?
  2. 我是否要在helper文件中创建class/public function并将其加载到需要的位置?
  3. 我是否要在library文件中创建class/public function并将其加载到需要的位置?
  4. 我是否在控制器中创建public function?

-额外- 我的假设是选项1,但我很好奇,如果我想在特定页面的其他位置显示此信息,该怎么办?我不想复制/粘贴代码块,因为这很草率.

我将如何设置它以便可以在需要的地方调用它? 例如$this->load->helper('check_for_sess');

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

class isLive
{   
    public function is_live() {

        $is_live = $this->session->userdata('email');
        $is_live = ucwords($is_live);
             if (!$is_live == null)
               echo 'Hello, '.$is_live.
               ' <b>(Not you? '.'<a href="' .base_url().'main/logout">Log Out</a>) </b>'; 

    }
}

view上,我尝试了此操作:

<?php 
    $isLive = new isLive;
    $isLive->is_live(); 
?>

但是这不起作用,并且会导致'函数objectdata()出现非对象错误'

有人可以解释实现我所需解决方案的正确方法和正确的语法.提前致谢!

-UPDATE--试图创建一个库-仍然出现错误.

#Created a library 
class CheckSess 
{   
    function IsLive() 
    {   
    $is_live = $this->session->userdata('email');
    $is_live = ucwords($is_live);

            if (!$is_live == null) 
            {
               $check_msg = 'Hello, '.$is_live.
               ' <b>(Not you? '.'<a href="' .base_url().'main/logout">Log Out</a>) </b>';
            }

    return $check_msg;
    }

}


#In the View
<?php echo $this->CheckSess->IsLive();  ?>

#in the controller
$this->load->library('CheckSess');

-更新-

class CheckSess {

    function IsLive() 
    {   
    $CI =& get_instance();
    $is_live = $CI->session->userdata('email');
    $is_live = ucwords($is_live);

            if (!$is_live == null) 
            {
               return 'Hello, '.$is_live.
               ' <b>(Not you? '.'<a href="' .base_url().'main/logout">Log Out</a>) </b>';
            }

    }

}

设置此^为libraries文件夹

view显示<?php echo $this->CheckSess->IsLive(); ?>

controller显示$this->load->library('CheckSess');

请告知.再次感谢!

错误---

(!)SCREAM:忽略了错误抑制 (!)致命错误:在第56行的C:\ wampserver \ www \ test-app \ application \ views \ homepage.php中的非对象上调用成员函数IsLive() 调用堆栈

时间记忆功能位置

1 0.0005 151432 {main}().. \ index.php:0 2 0.0014 187792 require_once('C:\ wampserver \ www \ test-app \ system \ core \ CodeIgniter.php').. \ index.php:202 3 0.0277 1537000 call_user_func_array().. \ CodeIgniter.php:359 4 0.0277 1537048 Main-> index().. \ CodeIgniter.php:359 5 0.0283 1540200 CI_Loader-> view().. \ main.php:8 6 0.0283 1540640 CI_Loader-> _ ci_load().. \ Loader.php:419 7 0.0287 1566584 include('C:\ wampserver \ www \ test-app \ application \ views \ homepage.php').. \ Loader.php:833

解决方案

在CodeIgniter中编写可重用的最佳方法是模型和库.

有了更好的库,因为您使用的代码和逻辑实际上不是MVC中的模型,但是对于CodeIgniter尤其是对于初学者,如果您不打算分发或共享,则可以在模型中编写它该代码以任何方式.

我建议您阅读有关CodeIgniter的内容的更多信息,您可以在SO或官方CI论坛上找到大量信息,但作为快速参考,我将写一份内容清单.

观看次数

静态,哑数据输出,格式化,迭代(用于显示表,列表等).

您仅需在此处使用一些基本的PHP函数,CodeIgniter帮助器,forforeachwhile循环和条件语句(ifcase)

控制器

表单数据捕获和验证,从模型捕获数据,将数据发送到视图,重定向.

模型

从数据库,远程源(API),文件中查询,读取,写入和更新数据.

助手

通常在视图中使用的常用功能-格式化HTML,将树解析和显示为列表<ul><li></li></ul>,其他功能(如

的简写功能)

function mydate() {
    return date("d.m.Y");
}

不使用任何CodeIgniter库/模型的东西(技术上可以使用,但在大多数情况下应避免使用).

图书馆

自定义类和对象,数据处理,API接口,上述复杂



如果要显示一些带有数据的视图文件,我会将其放在库中.您可以将其放入模型中.在我的项目中,当我使用某些部件时,我有一个库/模型(在我们的情况下,差异很小),可以称之为pmodel.

class Pmodel extends CI_Model() {
    function ShowHeader() {
        $data = array(
            'user' => $this->usermodel->GetCurrentUser()
        }
        $this->load->view('header', $data);
    }

    function ShowMyPart() {
        $is_live = $this->session->userdata('email');
        $is_live = ucwords($is_live);
        if (!$is_live == null)
               echo 'Hello, '.$is_live.
               ' <b>(Not you? '.'<a href="' .base_url().
               'main/logout">Log Out</a>) </b>'; 

    }
}

现在,如果您以前加载过视图文件,则可以在视图文件中的任何位置调用$this->pmodel->ShowMyPart()(无论如何,该类型的模型都应自动加载).

我会做一个小小的改变,因为这被认为是一种好习惯-绝不要在视图文件之外的任何地方echo进行任何操作,而是return值.

echo关键字更改为return,然后在视图文件中只需编写echo $this->pmodel->ShowMyPart().

为什么要这么做?因为,如果您想调用任何在加载标头和页脚(例如)之间回显控制器内容的方法,则CodeIgniter会在标头之前回显此方法,因为CodeIgniter不会立即回显您已加载的视图,因此会将它们保存为输出存储并在销毁自己之前立即发送最终的输出.在此处.

但是您甚至可以做得更好-使用视图文件来输出所需的任何数据,只需创建一个帮助程序并像在控制器中一样从模型/库中加载它即可.

希望有帮助!


编辑

对于您已编辑的问题,您的库出现错误的原因是,您的库不知道CodeIgniter的实例甚至存在,因为您没有像从模型中那样从库中扩展库.控制器.您不使用$this来引用库中的CodeIgniter类,因为$this是对库本身的引用,这是一个单独的类.要使用CodeIgniter类,您应该获得一个CodeIgniter实例:

$CI =& get_instance();

然后您可以使用$CI而不是$this通过更改以下行来调用CodeIgniter类:

$is_live = $this->session->userdata('email');

$is_live = $CI->session->userdata('email');

I am somewhat confused on the proper way to perform the following. Is this a class a function or an object? (Not sure) So here goes (please be kind) I'm learning codeigniter/php simultaneously.

    $is_live = $this->session->userdata('email');
    $is_live = ucwords($is_live);
            if (!$is_live == null)
                   echo 'Hello, '.$is_live.
                   ' <b>(Not you? '.'<a href="' .base_url().
                   'main/logout">Log Out</a>) </b>'; 

I wrote this code, which checks if a session is set and if true echo the details. I currently have this code on my view/main However I want to have this code displayed on all pages.

What is the proper way to do this?

  1. Do i create a view/header which is auto loaded on each page and insert this code there?
  2. Do I create a class/public function in a helper file and load it where needed?
  3. Do I create a class/public function in a library file and load it where needed?
  4. Do I create a public function in a controller?

-EXTRA- My assumption is option 1 but I'm curious what if I want to display this information in another location on a particular page? I don't want to have to copy/paste the code block because that is sloppy.

How would I set it up so that I can just call it where i need it? e.g. $this->load->helper('check_for_sess');

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

class isLive
{   
    public function is_live() {

        $is_live = $this->session->userdata('email');
        $is_live = ucwords($is_live);
             if (!$is_live == null)
               echo 'Hello, '.$is_live.
               ' <b>(Not you? '.'<a href="' .base_url().'main/logout">Log Out</a>) </b>'; 

    }
}

On the view I tried this:

<?php 
    $isLive = new isLive;
    $isLive->is_live(); 
?>

This however doesn't work and causes a ' function userdata() on a non-object error '

Can someone please explain the proper way to achieve my desired solution and the correct syntax. Thanks in advance!

-UPDATE-- Tried to create a library - still getting error.

#Created a library 
class CheckSess 
{   
    function IsLive() 
    {   
    $is_live = $this->session->userdata('email');
    $is_live = ucwords($is_live);

            if (!$is_live == null) 
            {
               $check_msg = 'Hello, '.$is_live.
               ' <b>(Not you? '.'<a href="' .base_url().'main/logout">Log Out</a>) </b>';
            }

    return $check_msg;
    }

}


#In the View
<?php echo $this->CheckSess->IsLive();  ?>

#in the controller
$this->load->library('CheckSess');

--UPDATE--

class CheckSess {

    function IsLive() 
    {   
    $CI =& get_instance();
    $is_live = $CI->session->userdata('email');
    $is_live = ucwords($is_live);

            if (!$is_live == null) 
            {
               return 'Hello, '.$is_live.
               ' <b>(Not you? '.'<a href="' .base_url().'main/logout">Log Out</a>) </b>';
            }

    }

}

Set this^ is the libraries folder

the view shows <?php echo $this->CheckSess->IsLive(); ?>

and the controller shows $this->load->library('CheckSess');

please advise. Thanks again!

ERROR---

( ! ) SCREAM: Error suppression ignored for ( ! ) Fatal error: Call to a member function IsLive() on a non-object in C:\wampserver\www\test-app\application\views\homepage.php on line 56 Call Stack

Time Memory Function Location

1 0.0005 151432 {main}( ) ..\index.php:0 2 0.0014 187792 require_once( 'C:\wampserver\www\test-app\system\core\CodeIgniter.php' ) ..\index.php:202 3 0.0277 1537000 call_user_func_array ( ) ..\CodeIgniter.php:359 4 0.0277 1537048 Main->index( ) ..\CodeIgniter.php:359 5 0.0283 1540200 CI_Loader->view( ) ..\main.php:8 6 0.0283 1540640 CI_Loader->_ci_load( ) ..\Loader.php:419 7 0.0287 1566584 include( 'C:\wampserver\www\test-app\application\views\homepage.php' ) ..\Loader.php:833

解决方案

The best ways to write such reusable in CodeIgniter are Models and Libraries.

With libraries being better because the code and logic you use isn't actually what models in MVC are, but with CodeIgniter and especially for a beginner it's pretty much ok to write this in models if you are not planning to distribute or share this code in any way.

I would suggest reading more on what goes where in CodeIgniter, you can find plenty information here, on SO or on official CI forums, but as a quick reference, I will write a list of what goes where.

Views

Static, dumb data output, formatting, iteration(for displaying tables, lists, etc.).

The only things you want to use here are some of the basic PHP functions, CodeIgniter helpers, for, foreach, while loops and conditionals (if, case)

Controllers

Form data capture and validation, catching data from models, sending data to views, redirects.

Models

Querying, reading, writing and updating data from databases, remote sources (APIs), files.

Helpers

Often used functions that are expected to be used in views - formatting HTML, parsing and displaying trees as lists <ul><li></li></ul>, shorthand functions for other functions like

function mydate() {
    return date("d.m.Y");
}

Stuff that does not use any of the CodeIgniter libraries/models (Technically it can use, but should be avoided in most cases).

Libraries

Custom classes and objects, data processing, API interfaces, complex of the aforementioned



If you want to display some view file with data, I would put it in a library. You can put it in to a model. In my projects when I use some parts, I have a library/model (difference in our case is minimal), lets call it pmodel.

class Pmodel extends CI_Model() {
    function ShowHeader() {
        $data = array(
            'user' => $this->usermodel->GetCurrentUser()
        }
        $this->load->view('header', $data);
    }

    function ShowMyPart() {
        $is_live = $this->session->userdata('email');
        $is_live = ucwords($is_live);
        if (!$is_live == null)
               echo 'Hello, '.$is_live.
               ' <b>(Not you? '.'<a href="' .base_url().
               'main/logout">Log Out</a>) </b>'; 

    }
}

Now anywhere in the view files you can call $this->pmodel->ShowMyPart() if you have loaded it before (models of this type should be autoloaded anyway).

There is one little change I would do as it's considered as good practice - never echo anything from anywhere but the view files, return values instead.

Change the echo keyword to return and in your view file simply write echo $this->pmodel->ShowMyPart().

Why should you do that? Because, if you would like to call any method that echoes something from the controller right between loading header and footer(eg.), CodeIgniter will echo this before the header as CodeIgniter does not echo your loaded views right away, it saves them to output storage and sends the finalized output right before destructing himself. More reading can be found here.

But you can do even better - use a view file to output any data you want, just create a helper and load it from your model/library as you do in your controllers.

Hope that helps!


EDIT

For your edited question, the reason why you are getting errors with your library is that your library doesn't know that an instance of CodeIgniter even exists as you are not extending your library from it, as you do with your models and controllers. You don't use $this to refer to CodeIgniter classes in your libraries, as $this is a reference to your library itself, which is a separate class. To use CodeIgniter classes you should get a CodeIgniter instance:

$CI =& get_instance();

And then you can use $CI instead of $this to call CodeIgniter classes by changing the line:

$is_live = $this->session->userdata('email');

to

$is_live = $CI->session->userdata('email');

这篇关于如何使此代码在不同的视图上可重用?正确的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆