How to have class loaded without using “use” but call it as if I used it

萝らか妹 提交于 2019-12-07 16:26:57

问题


I have studied these 2 sources, but none of those works for me.

http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html

Yii2 - How do I AutoLoad a custom class?

I have created custom helper class which I want to include in every model, controller and view in my application. I am using Yii2 advanced app version 2.0.11, IDE I am using is PHPStorm

QUESTION:

What I want to achieve is to not use use keyword at the beggining of every class but still be able to simply call AppHelper::myMethod() in models, controllers and views. How is that possible?

Closest I got it working was using this solution https://stackoverflow.com/a/35160997/5395463

All other solutions did not work for me. I am getting errors like:

PHP Fatal Error – yii\base\ErrorException 
Class 'frontend\controllers\AppHelper' not found

when I simply dont include use commons\commands\AppHelper; or when not using namespace as they suggest there with other settings:

Fatal error: Uncaught exception 'yii\base\UnknownClassException' 
with message 'Unable to find 'common\commands\AppHelper' 
in file: C:\xampp\htdocs\domain.com\web\common/commands/AppHelper.php.
 Namespace missing?' in ...

SOLUTION:

Thanks for your responses, I got it working finaly. https://stackoverflow.com/a/42330631/5395463 solution works best for me. So I removed namespace from that class, but left it in common\commands folder, added require to frontend/web/index.php and backend/web/index.php files (not sure if I should add it to yii file in root too, I didnt, so far it is working good anyways), and changed calls of class from AppHelper::myMethod() to \AppHelper::myMethod() looks like eveything is working now.


回答1:


Solution for not lazy coders:

  • create component with your class so you can use it like \Yii::$app->my_component
  • if even this is too much and your IDE is better than Windows Notepad prepare macro that will print this for you

Solution for lazy coders:

  • Save your class in single PHP file without namespace.
  • Modify you entry script to include this class - i.e. for Basic Project Template it's /web/index.php; add there

    require(__DIR__ . '/path/to/MyClass.php');
    

    For Advanced Project Template modify it properly.

  • Now you can use your class by calling it like \MyClass (yes, \ is required and yes, your IDE probably will modify it anyway to MyClass with use MyClass; added at the beginning.



回答2:


In Yii2 You can use an explicit way adding \ to full namespaced name

 \frontend\controllers\AppHelper

so you can sue your method

 \frontend\controllers\AppHelper::yourMethod(); 


来源:https://stackoverflow.com/questions/42330118/how-to-have-class-loaded-without-using-use-but-call-it-as-if-i-used-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!