开发者

CakePHP: Find if is mobile browser in a helper (no access to request handler)

开发者_Python百科

I need to know in a helper in a CakePHP application if the device is mobile, I would love to use $this->RequestHandler->isMobile(), but the request handler component is not available in helpers. Any ideas?

Thanks!


You can import the class and use it anywhere in the framework like so:

App::import('Component', 'RequestHandler'); // import class
$requestHandler = new RequestHandlerComponent(); // instantiate class
$isMobile = $requestHandler->isMobile(); // call method
var_dump($isMobile); // output: bool(true) or bool(false)

(Tested from helper and gives correct results for Firefox and iPhone)


Also, any options you set in the Controller::helpers property will be passed to the helper:

class AppController extends Controller {

    public $components = array(/*...*/, 'RequestHandler');

    public $helpers = array(/*...*/, 'MyHelper');

    public function beforeFilter() {
        $this->helpers['MyHelper']['mobile'] = $this->RequestHandler->isMobile();
    }

}

You can catch the options array in your helper's constructor:

class MyHelper extends AppHelper {

    protected $_defaultOptions = array('mobile' => false);

    public function __construct($options) {
        $this->options = array_merge($this->_defaultOptions, $options);
    }

}


The accepted answer suggests using a component inside a helper which should be avoided as components are for use solely in controllers and will result in errors as mentioned by Anupal.

The simple solution is to use the CakeRequest class that RequestHandlerComponent uses. So in your helper you can do:-

App::uses('CakeRequest', 'Utility');
$isMobile = (new CakeRequest())->is('mobile');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜