0
0

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 3 years have passed since last update.

【CakePHP4】ViewのHelperからComponentを読み込む方法

Posted at

読込したいComponent

SimpleComponent.php
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;

class SimpleComponent extends Component
{

    /**
     * getHalfPoint - 与えられた数字を半分にする
     *
     * @param  float
     * @return float
     */
    public function getHalfPoint(float $num):float
    {
        $return_num = $num / 2;
        return $review_ave;
    }
}

Helperの記述(ここ大事)

AppHelper.php
<?php
namespace App\View\Helper;
use Cake\View\Helper;
use App\Controller\Component\SimpleComponent;
use Cake\Controller\ComponentRegistry;

class AppHelper extends Helper
{
    /**
     * Point - SimpleComponentのgetHalfPointの使用
     */
    public function Point($point):float
    {
        $this->Simple = new SimpleComponent(new ComponentRegistry());
        $return_point = $this->Simple->getHalfPoint($point);

        return $return_point;
    }
}

1,読み込みたいComponentを指定すること

use App\Controller\Component\SimpleComponent; 

2.Componentをインスタンス化するために必要なComponentRegistryを読み込む

use App\Controller\Component\SimpleComponent; 

3.読み込みしたいComponentのインスタンス化

$this->Simple = new SimpleComponent(new ComponentRegistry());

Viewの記述(一応)

simple.php

<?php
    echo $this->App->Point(5);
    // 2.5が返ってくる
?>
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?