2016-09-21 71 views
0

这是我使用核心PHP开发Web应用程序的长期追求,并遵循最佳可行做法而不使用框架。通过更好地构建我的项目,我取得了许多成就。但是,获得一个干净的URL通常是大型应用程序的问题。使用Slim作为架构从头开始创建PHP Web应用程序

直到现在...我已经使用Slim Framework仅用于在我的Web应用程序之外创建RESTFUL服务。

我正在使用Slim Framework为PHP项目创建API。现在,我已经安装了Slim并运行良好。一般来说,我有我的路线与数据库交谈并做他们应该做的事情。我的问题与模块化代码有关。目前,我所有的路由都在我的index.php文件的根目录中定义。我非常想将这些分离出来,比如放到/ controllers文件夹中。

因为我喜欢Slim制作漂亮的网址的方式......我想知道是否可以使用Slim作为我的应用架构......并让我所有的页面或API都可以通过Slim index.php访问。

+0

你可能会检查其中一个Slim骨骼的灵感。 –

回答

1

很容易这里是我在最近的项目上采取的步骤。

首先让我们说你有一个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

你在哪里都被创建的苗条例如,你将需要获得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 

作为一个说明上述实例s可能是封闭的,但我当时没有看到这一点或做出决定。此外,还有一些延迟加载的方法,我还没有探究,请参阅here了解更多信息。

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

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

就算你不能有参数的作用,但我没有问题只是路过他们一起在请求中,然后从那里得到他们。

+0

您正在使用哪个修身版本。 –

+0

我在最新的3件事。 – nerdlyist

1

如果你想创建一个应用程序,没有框架,那么我会建议在寻找通过这个小小的GitHub库: https://github.com/PatrickLouys/no-framework-tutorial

会采用与您在路由方面设置了一切,再加上会使诸事通过公共文件夹中的index.php,像你的要求。