2

私は PHP を初めて使用するので、cakePHP フレームワークを使用して開始することにしました。

RequestHandlerComponent クラスのメソッドを呼び出して、ユーザーが最後に使用した IP アドレスやその他の情報を更新したいのですが、これを配置するのに最適な場所は、ユーザーの beforeSave() メソッドであると考えましたモデル。

getClientIP メソッドを呼び出す方法がわかりません。

そうでなければコントローラーに入る通常のコードは機能しません。コントローラーではなくモデルにいる場合、このクラスを呼び出す別の方法はありますか?

クラスレベル:

var $components = array('RequestHandler');

そして関数で:

$this->data['User']['lastActiveIP'] = $this->RequestHandler->getClientIP();

与えます:

Undefined property: User::$RequestHandler
Call to a member function getClientIP() on a non-object
4

2 に答える 2

4

Components, by design, aren't available to models (without bypassing MVC convention - which you can do, of course). If you chose to force it to be available, look into ClassRegistry::init(). A better solution, I think, would be to employ the RequestHandler component in your controller (where it's meant to be used), set the lastActiveIp value in the controller (exactly as you've shown in your own example code) and pass the entire data array along to the model.

Now your component is being used where it should be and the model gets to remain ignorant about where it gets its data. At the risk of oversimplification, all the model should know is what to do with the data once it arrives; let the controller worry about collecting and packaging the data.

于 2009-08-03T11:44:10.957 に答える
1

env('REMOTE_ADDR')ロブの答えに加えて、一般的な変数または同様の変数を使用するコードを自分で少しまとめるだけで十分かもしれません。コードを見てくださいRequestHandler。それほど複雑なことはしていません。

コンポーネントを静的に呼び出すこともできます。これは、モデルでインスタンス化するよりもわずかに優れています (ただし、MVC には違反しています)。テストされていませんが、動作するはずです:

App::import('Component', 'RequestHandler');
RequestHandlerComponent::getClientIp();
于 2009-08-03T11:54:25.487 に答える