2

我不是 PHP 新手,但我是 PSR 新手。我已经阅读了其中的一些内容,我想尝试遵循这个编码标准,但我有点困惑如何实现它。因此,我需要你们根据我将提供的示例就如何实现它提供一个简单的建议。

目录结构

 /models
    User.php
 /controller
    controller.php
 /view
    index.php

模型.php

Class User
{
  public function foo()
  {
    // Do something
  }
}

如何在 PSR-0 方法中在我的 controller.php 上调用该类?我读过类似的东西

namespace, use

和这个

   function autoload($className)
   {
    $className = ltrim($className, '\\');
    $fileName  = '';
    $namespace = '';
    if ($lastNsPos = strrpos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

    require $fileName;
   }

但我不知道如何以及在哪里放置这些代码。

谢谢!

4

2 回答 2

1

It means you have a folder for every namespace you are using.

So if you define a class in a namespace say:

<?php
namespace Nicemodels;

class Niceuser { ... }

Then the file Niceuser.php needs to be in .../models/Nicemodels/

You still need to make sure you handle the models directory correctly. You could start one on a higher level and put all your models in the Models namespace (recommended).

So above example becomes:

<?php
namespace Models\Nicemodels;

class Niceuser { ... }

The use statement is used to import classes from another namespace:

<?php
namespace Models\Nicemodels;

use Models\Normaluser

class Niceuser extends Normaluser { ... }

You autoloader reflects this namespace to directory behaviour in the line

$fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;

Here you convert namespace separators '\' into directory separators.

You need to tell your autoload the starting point of all this. So you if you don't use the Models namespace you need to point to your models/ folder as start. And you need to make sure of the case you start your filenames with. Otherwise the autoloader will not find your classes.


If you want to use such a class in your controllers you do:

$user = new \Models\Nicemodels\Niceuser();

You can shorten that, if you import the class:

use Models\Nicemodels\Niceuser;
...
$user = new Niceuser();
于 2014-06-16T07:26:53.970 回答
0

您需要使用 spl_autoload_register() 函数注册您的自动加载器。

你在文档中有一些很好的例子:http ://www.php.net/manual/en/function.spl-autoload-register.php

于 2014-06-16T07:38:57.870 回答