我如何扩展自己的库



我是新的codeigniter,并希望添加一个库到我的第一个扩展另一个库的ci应用程序

class Mylib {}

/应用程序/图书馆/Mynewlib.php:

class Mynewlib extends Mylib{}

我要把Mylib.php和我如何加载Mylib?

谢谢!

我仍然在寻找这种情况下的最佳实践。

在我的情况下,我有两个类应该从父扩展。(支付-父类;Payment_paypal -与Paypal互动;Payment_nganluong -与Ngan Luong互动,我的国内网关)对于每个支付网关,我必须编写一些属性,处理方法,但几乎基本属性和主题方法是相同的。

我的解决方案:我创建了4个文件:

  1. Payment_base.php

    class Payment_base { // base properties and method }

  2. Payment.php

    require_once (APPPATH.'/libraries/Payment_base.php'); // this is an instance of payment_base, // when you want to use base method and properties // just call $payment->... // class Payment extends Payment_base { public function __construct(){ parent::__construct() } }

  3. Payment_paypal.php

    require_once (APPPATH.'/libraries/Payment_base.php'); class Payment_paypal extends Payment_base{} ////////////////////////////////////////// require_one 'Payment_base.php'; class Payment_paypal extends Payment_base { // properties and method }

4, Payment_nganluong.php

require_once (APPPATH.'/libraries/Payment_base.php');
class Payment_nganluong extends Payment_base { 
// properties and method
}

就是这样,在controller中:

$this->load->library('payment');
$this->load->library('payment_paypal');
$this->load->library('payment_nganluong');
$this->payment->myMethod(); // base method
$this->payment_paypal->charge(); // call to paypal to charge money
$this->payment_nganluong->checkout(); // check out with Ngan Luong
// no need to load and use payment_base

这对我很有用。

库文件Mylib.php

class Mylib {
   function test() 
   {
       return 1;
   }
}

库文件Mynewlib

require_once('Mylib.php');   
class Mynewlib extends Mylib{}
控制器

$this->load->library('Mynewlib');
echo $this->Mynewlib->test();

application/libraries/mylib.php中创建文件

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MyLib
 {
    function __construct() 
    {
         // initialize variables if you want
    }
    public function  my_function($something)
    {
    $out = $something . " World";
    return $out;
    }
}
/* End of file mylib.php */

然后在控制器中像这样调用库

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class my_controller extends CI_Controller 
{
    public function index()
    {
        $this->load->library('mylib'); // call the custom class MyLib
        $term = $this->mylib->my_function("Hello");
        echo $term; // Hello World
    }
}
/* End of file my_controller.php */
/* Location: ./application/controllers/my_controller.php */

希望有帮助

详情请参阅http://www.codeigniter.com/userguide2/general/creating_libraries.html

你可以使用get instance in library来加载另一个库

<?php
class MyLib {
public function __construct() {
    $this->CI =& get_instance();
    $this->CI->load->library('mylib2');
}
public function something() {
   $this->CI->mylib2->some_function();
}
}

相关内容

  • 没有找到相关文章

最新更新