1

名前空間を使用して将来の開発を容易にし、クラス名を再利用できるようにするために作成したアプリの再構築を開始したところです。

基本的に私のコードは次のとおりです。

<?php
session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

use core\marketing as marketing;
use core\security as security;
use core\structure as structure;
use core\data as data;

include 'marketing\cleanurl.php';
?>

これを実行するとすぐに、次のエラーが表示されます。

警告: include(marketing\cleanurl.php): ストリームを開けませんでした: No such file or directory in /var/www/index.php on line 27 Warning: include(): Failed open 'marketing\cleanurl.php' for include (include_path='.:/usr/share/php:/usr/share/pear') /var/www/index.php の 27 行目

私のディレクトリ構造は、ネットで読んだ名前空間と一致しています。

ここで、ディレクトリに一致するようにインクルードを変​​更すると、つまり

include 'core/marketing/cleanurl.php';

次のエラーが表示されます

解析エラー: 構文エラー、予期しない T_CLASS、T_NS_SEPARATOR または ';' が必要です または /var/www/twiggled/core/marketing/cleanurl.php の 4 行目の '{'

これはすべてのクラスを呼び出すために require_once を使用していたときにすべて機能しましたが、システムのこの制限された拡張が見つかり、変更に時間がかかり、私が使用した他の言語で常に優れていた名前空間を使用したいと考えました。

4

1 に答える 1

2

OPがそれを求めたので、オートロードを使用した更新された回答があります。

注: もちろん、作業を容易にするために、このような複雑な構造は必要ありません。ただし、これは物事がどのように連携するかの例にすぎません(オートロード、require、静的メソッドなど)。

ブートストラップ / 自動ロード

/var/www/somedir/Twiggled/bootstrap.php

<?php
namespace Twiggled;

require_once __DIR__ . '\Common\AutoLoader.php';

$autoloader = new \Twiggled\Common\AutoLoader(__NAMESPACE__, dirname(__DIR__));
$autoloader->register();

/var/www/somedir/Twiggled/Common/AutoLoader.php

<?php
namespace Twiggled\Common;

/**
 * PSR-0 Autoloader
 *
 * @package    Common
 */
class AutoLoader
{
    /**
     * @var string The namespace prefix for this instance.
     */
    protected $namespace = '';

    /**
     * @var string The filesystem prefix to use for this instance
     */
    protected $path = '';

    /**
     * Build the instance of the autoloader
     *
     * @param string $namespace The prefixed namespace this instance will load
     * @param string $path The filesystem path to the root of the namespace
     */
    public function __construct($namespace, $path)
    {
        $this->namespace = ltrim($namespace, '\\');
        $this->path      = rtrim($path, '/\\') . DIRECTORY_SEPARATOR;
    }

    /**
     * Try to load a class
     *
     * @param string $class The class name to load
     *
     * @return boolean If the loading was successful
     */
    public function load($class)
    {
        $class = ltrim($class, '\\');

        if (strpos($class, $this->namespace) === 0) {
            $nsparts   = explode('\\', $class);
            $class     = array_pop($nsparts);
            $nsparts[] = '';
            $path      = $this->path . implode(DIRECTORY_SEPARATOR, $nsparts);
            $path     .= str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';

            if (file_exists($path)) {
                require $path;
                return true;
            }
        }
        return false;
    }

    /**
     * Register the autoloader to PHP
     *
     * @return boolean The status of the registration
     */
    public function register()
    {
        return spl_autoload_register(array($this, 'load'));
    }

    /**
     * Unregister the autoloader to PHP
     *
     * @return boolean The status of the unregistration
     */
    public function unregister()
    {
        return spl_autoload_unregister(array($this, 'load'));
    }
}

パッケージファイル

/var/www/somedir/Twiggled/Core/Helper/Strings.php

<?php
namespace Twiggled\Core\Helper;

class Strings
{
    // Note: Eventhough the method use a global PHP function name,
    // there is no problem with it - thanks to namespace.
    public static function str_replace($str) 
    {
        $str = preg_replace('/\s/', '_', strtolower($str));
        return preg_replace('/[^a-zA-Z_]/', '', $str);
    }
}

/var/www/somedir/Twiggled/コア/マーケティング/Cleanurl.php

<?php
namespace Twiggled\Core\Marketing;

use \Twiggled\Core\Helper\Strings as HelperStrings;

class Cleanurl 
{
    const BASE_URL = 'http://example.com/';
    public $cleanPath;

    public function __construct($str) 
    {
        $this->cleanPath= HelperStrings::str_replace($str);
    }
}

ロードして使用します。

/var/www/somedir/index.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('date.timezone', 'Europe/Berlin');

// Bootstrap the package / register autoloader
require_once __DIR__ . '\Twiggled\bootstrap.php';

use \Twiggled\Core\Marketing as Marketing;

try {
    $obj = new Marketing\Cleanurl('$This w-ork5s!');

    // prints 'http://example.com/this_works'.
    echo Marketing\Cleanurl::BASE_URL . $obj->cleanPath; 
} 
catch (\Exception $e) { }
于 2013-01-31T03:28:20.867 に答える