title: Yii2 - How do I AutoLoad a custom class?
body: <p>I have created the following custom class that I'd like to use in my Yii2 application:</p>
  
  <p><em>@common/components/helper/CustomDateTime.php</em></p>
  
  <pre><code>namespace common\components\helper;
  class CustomDateTime{function Now() {...}}
  </code></pre>
  
  <p>I want to use this class like this:</p>
  
  <pre><code>public function actionDelete($id)
  {
      $account = $this-&gt;findModel($id);
      $account-&gt;archived = 1;
      $account-&gt;archived_date = CustomDateTime::Now();
      $account-&gt;save();
  
      return $this-&gt;redirect(['index']);
  }
  </code></pre>
  
  <p>In my @common/config/bootstrap.php file I've created a classMap according to this <a href="http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html">http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html</a>. </p>
  
  <pre><code>Yii::$classMap['CustomDateTime'] = '@common/components/helper/CustomDateTime.php';
  </code></pre>
  
  <p>But I am getting the error: <em>Class 'app\controllers\myapp\CustomDateTime' not found</em></p>
  
  <p><strong>QUESTION:</strong> How do I create a classMap so that I don't have to use the <strong>use</strong> statement at the beginning of every controller to access my custom class?</p>
  
  <p>Yii 1.1 used to have an option in the config file to 'import' a set of code so that a class file could be autoloaded when it was called.</p>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>Many thanks to @Animir for redirecting me back to the original documentation.  <a href="http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html">http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html</a>. </p>
  
  <p>I found that I can use the following in my <em>@common/config/bootstrap.php</em> file</p>
  
  <pre><code>Yii::$classMap['CustomDateTime'] = '@common/components/helper/CustomDateTime.php';
  </code></pre>
  
  <p>BUT - it only works when the the CustomDateTime.php file does NOT have a declared namespace.</p>
  
  <pre><code>//namespace common\components\helper;
  class CustomDateTime{function Now() {...}}
  </code></pre>