使用Slim作为架构从头开始创建PHP Web应用程序


Creating a PHP Web app from scratch using Slim as Architecture

这是我使用核心PHP开发web应用程序并遵循最佳实践而不使用框架的长期追求。通过更好地组织我的项目,我已经取得了很多成就。然而……对于大型应用程序来说,获得一个干净的URL通常是个问题。

直到现在…我只使用Slim框架在我的web应用程序之外创建RESTFUL服务。

我正在使用Slim框架为PHP项目创建api。现在,我已经安装了Slim,运行良好。我让我的路由与数据库对话并做它们应该做的事情。我的问题与代码的模块化有关。目前,所有的路由都是在根目录下的index.php文件中定义的。我很想把它们分开,比如放到/controllers文件夹中。

因为我喜欢Slim制作非常好的url的方式…我想知道是否有可能使用Slim作为我的应用程序架构…让我所有的页面或api都可以通过Slim index.php访问。

很容易,这是我在最近的一个项目中采取的步骤。

首先假设你有一个HomeActionController

class HomeActionController {
    //The below line I have moved into an abstract Controller class
    public $view = null;
    //This is using Slim Views PhpRenderer
    //This allows for a controller to render views can be whatever you need
    //I did not like the idea of passing the whole DC it seemed overkill
    //The below method I have moved into an abstract Controller class
    public function __construct('Slim'Views'PhpRenderer $view = null){        
        if($view != null){
            $this->view = $view;
        }
    }  
    //View could be any action method you want to call it.
    public function view(Request $request, Response $response, array $args){
         $data['user'] = "John Doe";
         return $this->view->render($response, 'templates/home.php', $data);
    }
}

现在你需要能够从路由中调用这个控制器的实例所以你需要将控制器添加到DC

无论您在哪里创建slim实例,您都需要获取DC并添加控制器实例:

$app = new 'Slim'App($config['slim']);
// Get Dependency Container for Slim
$container = $app->getContainer();
$container['HomeActionController'] = new Controller'HomeActionController($container['view']); //Notice passing the view

值得注意的是,上面的实例化本可以是闭包,但我当时没有看到它们的意义。此外,还有一些延迟加载的方法我还没有研究过,详见此处。

现在你需要做的最后一件事是能够在路由上调用这些,这不是一个很大的挑战。

$app->get('/home', 'HomeActionController:view');

当然你不能有一个带有参数的动作,但我没有遇到过一个问题,只是在请求中传递它们,然后从那里获取它们。

如果你想创建一个没有框架的应用程序,那么我建议你看看这个小github repo:https://github.com/PatrickLouys/no-framework-tutorial

它会帮你在路由方面设置所有东西,plus会让所有东西都通过index.php的公共文件夹