2017-02-24 101 views
2

我試圖根據這個使用AWS SDK: http://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/installation.htmlPHP自動加載自己的類和AWS SDK

我已經試過.phar文件解包拉鍊都,但我遇到的問題。

我使用__autoload函數在PHP這樣的:

// 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方法,您只能有一個自動加載器,並且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手冊的自助式自動加載器類的示例。

<?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

非常歡迎。 –