Codeigniter 2.0 third_party folder

后端 未结 4 1090
無奈伤痛
無奈伤痛 2020-12-14 08:26

What is this the third_party folder in codeigniter 2.0 and how to use that?

4条回答
  •  伪装坚强ぢ
    2020-12-14 08:59

    As John explained in his answer, a single-file library can be loaded by placing it in the libraries folder:

    $this->load->library('my_app');
    

    Multiple single-file libraries can be loaded similarly with an array:

    $this->load->library(['email', 'table']);
    

    However, if you have a folder full of classes to be loaded not related to CodeIgniter, you can still place them in the third_party folder, but do not use $this->load->add_package_path() (it expects a CI structure inside the new third_party package, i.e. with models, configs, helpers, etc.).

    I leave an example, Stripe API has a lib folder and an init.php, so I did the following:

    1. updated init.php references from dirname(__FILE__) . '/lib/ to dirname(__FILE__) . '/) and placed the file in the third_party/stripe folder together with all contents of the lib folder;
    2. Create, for example, a libraries/Stripe.php;
    3. This would be its constructor:

      public function __construct()
      {
        $this->CI =& get_instance();
        require_once(APPPATH.'third_party/stripe/init.php');
        \Stripe\Stripe::setApiKey($this->CI->config->item('stripe_key_secret'));
        if(ENVIRONMENT === 'development'){
          \Stripe\Stripe::setVerifySslCerts(false);
        }
      }
      
    4. Add to it functions that invoke directly Stripe classes, simple e.g.:

      public static function create_customer($email, $token) {
        $stripe_result = FALSE;
        try {
          $stripe_result = \Stripe\Customer::create([
            'email' => $email,
            'description' => "Customer for $email",
            'source' => $token // obtained with Stripe.js
          ]);
        } catch(\Stripe\Error\Card $e) {
          return 'Error ' . $e->getHttpStatus() . ': '.
            $e->stripeCode .  ' -> '.
            var_export($e->getJsonBody()['error'], TRUE);
        } catch (Exception $e) {
          return 'Something else happened, completely unrelated to Stripe -> '.
            var_export($e, TRUE);
        }
        return $stripe_result;
      
    5. load the library on one of your controllers and invoke the method:

      $this->load->library('stripe');
      Stripe::create_customer($someones_email, $someones_token); // you can use the result
      

    Just also leaving the updated URL: CodeIgniter's Loader Class documentation.

提交回复
热议问题