1

私は Cakephp 2.x で開発したサイトを持っています。私は自分のコントローラーに次のような別のコントローラーの関数を呼び出したいと思っています:

class ProductsController extends AppController {
    public $name = 'Products';
    public $scaffold;
    public $uses = array('Product','Unit');

        public function testFunction(){
             $this->loadModel('Unit');
             $this->Unit->test();
        }
}

UintController.php への関数テストは次のとおりです。

public function test(){
                 echo("test");
            }

私のモデル名は Product と Unit です。関数 test を呼び出すと、次のエラーが表示されます。

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'prova' at line 1

関数では今は空ですが、このエラーが発生します。私は試してみました:

public $uses = array('Unit');

$uses で行をキャンセルします。

どうすれば解決できますか?

4

1 に答える 1

4

別のコントローラーから関数を呼び出すには、requestActionを使用できます。

意味

「この関数は、任意の場所からコントローラのアクションを呼び出し、アクションからデータを返します。渡された $url は、CakePHP 相対 URL (/controllername/actionname/params) です。追加のデータを受信コントローラ アクションに渡すには、$options に追加します。配列"。

使用法

コードは次のようになります。

class ProductsController extends AppController
{
    public $name = 'Products';
    public $scaffold;
    public $uses = array('Product','Unit');

    public function testFunction() {
        // Calls the action from another controller            
        echo $this->requestAction('/unit/test');             
    }
}

そして、でUnitController

class UnitController extends AppController
{
    public function test() 
    {
        return 'Hello, I came from another controller.';
    }
}

警告

CakePHPクックブックで述べたように:

「requestAction をキャッシュせずに使用すると、パフォーマンスが低下する可能性があります。コントローラーまたはモデルでの使用はほとんど適切ではありません」。

あなたに最適なソリューション

しかし、あなたにとって最善の解決策は、モデル内に関数を作成し、次のようにコントローラーから呼び出すことです。

class ProductsController extends AppController {
    public $name = 'Products';
    public $scaffold;
    public $uses = array('Product','Unit');

    public function testFunction() {
         echo $this->Unit->test();
    }
}

そしてUnitモデルでは:

class Unit extends AppModel
{
    public function test(){
        return 'Hello, I came from a model!';
    }    
}
于 2012-11-02T01:37:53.047 に答える