gpt4 book ai didi

php - 在 Codeigniter 中使用 PHP 接口(interface)

转载 作者:可可西里 更新时间:2023-10-31 22:40:53 25 4
gpt4 key购买 nike

我正在尝试了解如何在我的 MVC 设计中使用 PHP 接口(interface)。我想确保设计强制执行一个接口(interface),以便任何新模块都遵循该接口(interface)。

例如:

<?php

interface BaseAPI {
public function postMessage($msg);
}

class ServiceAPI implements BaseAPI {
public function postMessage($msg) { return $msg; }
}

class Service_Two_API implements BaseAPI {
public function postMessage($msg) { return "can't do this: ".$msg; }
}

?>

我想在 CI 中执行此操作。可能吗?应该怎么设计?

最佳答案

这是让 CodeIgniter 正确加载接口(interface)的方法

在您的 application/config/autoload.php 中:

// Add "interface_autoloader" to your models array
$autoload['model'] = array('interface_autoloader');

现在在您的应用程序/模型文件夹“interface_autoloader.php”中创建一个新类:

<?php

class Interface_autoloader {

public function __construct() {
$this->init_autoloader();
}

private function init_autoloader(){
spl_autoload_register(function($classname){
if( strpos($classname,'interface') !== false ){
strtolower($classname);
require('application/interfaces/'.$classname.'.php');
}
});
}

}

现在在您的应用程序文件夹中创建一个名为“interfaces”的新文件夹: Example of Interface Usage with CodeIgniter

然后只需将您的界面添加到“interfaces”文件夹中,您应该就可以正常使用它们了。

关于php - 在 Codeigniter 中使用 PHP 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2844049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com