2017-04-21 11 views
0

我正在用PHP构建api,我不熟悉扩展类或使用特征。目前我正在使用特质来更好地构建我的主要API课程。为主类扩展类和使用特性

请参阅下面的当前工作方式。我想知道是否可以在API课程中创建一门课。例如,它负责webhook方法。这需要有权访问当前实例的路由器和api上的所有方法。

当人们访问/v1/{method}/{verb}/{args}

if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) { 
    $_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME']; 
} 

try { 
    $API = new API($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']); 
    echo $API->processAPI(); 
} 

catch (Exception $e) { 
    echo json_encode(['error' => $e->getMessage()]); 
} 

路由器类的API

abstract class router { 
    /* 
     Methods which seek out 
     * method 
     * verb 
     * args 

     And do authentication 
    */ 
} 

我的主要API类

class API extends router { 
    // some generic methods specifically for this class 

    // Other methods but in different files (for readability and oversight) 
    use otherMethod1; 
    use otherMethod2; 
    // ... 
} 
+0

什么是你的问题) –

+0

@VladimirKovpak IKR ......基本上要多次扩展类,同时能够继承?父函数和实例的变量。如果这更有意义-_-我不知道该怎么解释这个! – NealVDV

+1

@NealVDV你应该创建你的webhook类的对象并将它注入API。您可以通过构造函数或setter方法传递它。 –

回答

0

您可以将webhook类对象注入到您的API类中。小例子,如要求。

class Webhook { // some methods } 

    class API extends router { 
     private $webhook; 

     public function __construct(Webhook $webhook) 
     { 
      $this->webhook = $webhook; 
     } 
     // some generic methods specifically for this class 

     public function useWebhook() 
     { 
      $result = $this->webhook->someWebhookMethod(); 
      // ... 
     } 

     // Other methods but in different files (for readability and oversight) 
     use otherMethod1; 
     use otherMethod2; 
     // ... 
    } 

当你可以创建你的对象是这样

$webhook = new Webhook(); 
$api = new API($webhook); 

$api->useWebhook(); 

你在找这个?

你可以阅读更多关于这种方法叫做“依赖注入”就在这里:http://php-di.org/doc/understanding-di.html