9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FuelPHPでTraitを使う方法

Posted at

手順

  • 下記のようにapp以下にtraitを書くためのファイルを作る。
fuel
 |-app
    |-traits.php

とりあえずtraits.phpには下記のようなソースを書いておく

traits.php
<?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にtraitを読み込ませておく
bootstrap.php
...

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宣言する
class MyClass{
  use SingletonTrait;
  ...
}

補足

上記では、traits.phpというファイルを作りましたが、他にも、appの下にtraitsというフォルダを作って、そのフォルダの中にファイルを作っていく方法もよいと思います。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?