2017-02-24 12 views
2

PHPの自動ロード独自のクラスとAWS SDK

私はこのようにPHPで__autoload関数を使用します。

// autoload classes 
function __autoload($class) { 
    require_once ('./system/classes/'.strtolower($class).'.php'); 
} 

これ自体は正常に動作します。しかし、私はそうのようなSDKが含まれています

require '/path/to/aws.phar'; 

私のシステムは、任意のより多くの(私はAWSのSDKが含ま時点でまだ呼び出されていないもの)を自分のクラスを見つけることができません。

私には何が欠けていますか?私は何を間違えたのですか?

+0

ははるかに、最も簡単に作曲いずれかを使用します。 – Augwa

+0

あなたにとって最適なものを使用してください。 –

答えて

2

__autoloadメソッドを使用すると、オートローダーが1つしかなく、awsが独自のオートローダーを追加する必要があるからです。 spl_autoload_registerを使用する方がはるかに優れています。これは複数の自動ロード機能を可能にするため、aws.pharが独自の機能を追加した場合でも使用できます。

これを試してみてください:

spl_autoload_register(function ($class) { 
    require_once ('./system/classes/'.strtolower($class).'.php'); 
}); 

はここに、この上のドキュメントを参照してください: http://php.net/manual/en/function.spl-autoload-register.php

+0

私は多くのことを学ぶことがあると思います。多くのありがとう、私はこれを試してみよう! – gregoff

+0

Composer https://getcomposer.org/を見て、他のライブラリの依存関係をphpで管理するだけでなく、自分のクラスを自動的に自動ロードするように設定することもできます。 – Theo

+0

しかし、オートローディングがどのように機能するかは分かりません。 –

1

をそれはPHP-FIG SP4 autoload標準を学び、それを自分で行うことは困難ではありません。これはspl_autoload_register()を使用し、複数のオートローダーを使用できます。ここでは、PHP-FIG標準とPHPマニュアルを読んだだけのdo-it-yourselfオートローダクラスの例を示します。

<?php 
namespace Acme\Framework; //Just to use namespaces in this example. 

class Autoloader 
{ 
    private function __construct() 
    { 
     ; 
    } 

    private function __clone() 
    { 
     ; 
    } 

    private static function autoload($qualifiedClassName) 
    { 
     $nsPrefix = 'Acme\\'; 
     $baseDir = 'C:/public/www/acme/src/'; // /public/www/acme/src/ 
     $nsPrefixLength = strlen($nsPrefix); 

     if (strncmp($nsPrefix, $qualifiedClassName, $nsPrefixLength) !== 0) { 
      return; //Go to next registered autoloader function/method. 
     } 

     $file = $baseDir . str_replace('\\', '/', substr($qualifiedClassName, $nsPrefixLength)) . '.php'; //substr() returns the string after $nsPrefix. 

     if (!file_exists($file)){ 
      echo "<h1>$file</h1>"; 
      throw new \RuntimeException("The file {$file} does not exist!"); 
     } 

     if (!is_file($file)){ 
      throw new \RuntimeException("The file {$file} is not a regular file!"); 
     } 

     if (!is_readable($file)){ 
      throw new \RuntimeException("The file {$file} is not readable!"); 
     } 

     require $file; 
    } 

    public static function init() 
    { 
     /* 
      Just make another method in this class and alter this code 
      to run spl_autoload_register() twice. 
     */ 

     if(!spl_autoload_register(['self', 'autoload'])) 
     { 
      throw new \RuntimeException('Autoloader failed to initialize spl_autoload_register().'); 
     } 
    } 
} 

ブートストラップ時にこのように使用します。

require 'Autoloader.php'; //Autoloader for objects. 
Autoloader::init(); 

これは、別のディレクトリのコードに対して別のオートローダーをサポートするように変更することができます。

これは役に立ちましたと思います。あなたに幸運をもたらし、あなたのプロジェクトが成功するかもしれません!

敬具、

アンソニー・ラトリッジ

+0

参考にしてください!どうもありがとう! – gregoff

+0

あなたは大歓迎です。 –

関連する問題