Php 如何从Silex中的自定义文件/类连接到数据库
我第一次尝试这个迷你框架,这是我第一次使用justa a框架:)Php 如何从Silex中的自定义文件/类连接到数据库,php,doctrine,silex,Php,Doctrine,Silex,我第一次尝试这个迷你框架,这是我第一次使用justa a框架:) 我将条令服务添加到index.php文件中,如下所示: $app->register(new Silex\Provider\DoctrineServiceProvider(), array( 'db.options' => array( 'driver' => 'pdo_sqlite', 'path' => __DIR__.'/../include/dat
我将条令服务添加到index.php文件中,如下所示:
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'db.options' => array(
'driver' => 'pdo_sqlite',
'path' => __DIR__.'/../include/database.sqlite',
),
));
$myClass = $app['my_class'];
我用一个类创建了一个新文件,该类使用一个静态方法重新返回数组
<?php
namespace MyNameSpace;
class myClass{
static function getStuff(){
return array(1 => array('foo'=> 'bar',
'bar' => 'foo',
)
);
}
}
您需要知道的第一件事是,访问
$app
是一种不好的做法。在可能的情况下,您应该进行DI。如果您真的想这样做,请检查下面的代码
在index.php
(通常是bootstrap.php
)内声明一个新服务:
$app['my_class'] = $app->share(function() use ($app) {
// Retrieve the db instance and create an instance of myClass
return new \MyNameSpace\myClass($app['db']);
});
在myClass上添加构造函数:
namespace MyNameSpace;
class myClass
{
/**
* The connection
*
* @var \Doctrine\DBAL\Connection
*/
private $db;
/**
* Constructor
*
* @param $db \Doctrine\DBAL\Connection
*/
public function __construct($db)
{
$this->db = $db;
}
// ...
}
然后您可以检索myClass
的完全初始化实例,如下所示:
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'db.options' => array(
'driver' => 'pdo_sqlite',
'path' => __DIR__.'/../include/database.sqlite',
),
));
$myClass = $app['my_class'];
很抱歉我的无知,但我没有boostrap.php文件。每个人都在谈论这个文件,但没有人解释该怎么称呼它。我用我的目录结构编辑第一个答案,如果你能告诉我在哪里调用引导文件,谢谢1:现在检索数据库连接,而不是
$app
edit 2:重命名bootstrap.php
为index.php
,那么在Silex的新闻版本中,引导映射是index.php?而autoload.php是?我不会在这方面做太多支持,所以现在学习Silex最好的方法就是看看别人是怎么做的!这是一个很好的起点,因为它使用了大多数Silex功能,并且是最新的。