如何在FuelPHP中使用Trait


步骤

  • 创建一个文件以在应用程序下写特征,如下所示。
1
2
3
fuel
 |-app
    |-traits.php

目前,在traits.php中写以下源代码

traits.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
trait SingletonTrait {

    private static $self = null;

    protected function __construct(){}

    private function __clone(){}

    private function __wakeup(){}

    public static function getInstance(){
        if(is_null(self::$self)){
            self::$self = new self;
        }
        return self::$self;
    }
}
  • 接下来,让FuelPHP加载特征。

bootstrap.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
...

Autoloader::add_classes(array(
    // Add classes you want to override here
    // Example: 'View' => APPPATH.'classes/view.php',
));

// Register the autoloader
Autoloader::register();

// Load trait
\Fuel::load(APPPATH.DS.'traits.php');

...
  • 最后,在要使用SingletonTrait的类中声明use
1
2
3
4
class MyClass{
  use SingletonTrait;
  ...
}

补充

在上面,我创建了一个名为traits.php的文件,但是我认为在app下创建一个名为traits的文件夹并在该文件夹中创建文件也是一个好主意。