I can't find where to connect to the database in ZF2, where to create the application.ini to setup required data or in the module->bootstrap method, please help
As others have pointed out, you can add something like the following to your config/autoload/global.php or config/autoload/local.php.
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=mydb;host=localhost',
'username' => 'root',
'password' => '',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
Note that it is best practice to add sensitive information (e.g. the password) to the local.php file. The reason is that this file should be ignored by version control software and is ignored by Git by default if you are using the Zend Skeleton Application due to a .gitignore file.
To use the connection, you can fetch the database adapter from the service manager. For instance, you can do the following in a controller action:
public function someAction() {
$dbAdapter = $this->serviceLocator->get('Zend\Db\Adapter\Adapter');
// Do something with the database adapter, e.g.:
$dbAdapter->query('SELECT username FROM user WHERE id = ?', array(37));
}
The manual should get you started on how you can use the database adapter to execute queries; you will probably want to make use of Zend\Db\Sql, so the above is just an example. Note that you would ideally not access the database (i.e. execute database queries) directly within your controllers, but the above is just an example; it is quite easy to inject the database adapter into a Data Access Layer (DAL) or service layer if you are using any of those design patterns.
What happens above is that the Zend\Db\Adapter\AdapterServiceFactory is invoked. This happens because the class implements the Zend\ServiceManager\FactoryInterface, which the service manager checks against (see the service manager's source code for more information).
The Zend\Db\Adapter\AdapterServiceFactory factory fetches the configuration from the service manager and reads the 'db' key. This configuration (as shown in the first code example) is then passed to the Zend\Db\Adapter\Adapter's constructor which configures the instantiated database adapter.
So, all you have to do is to configure your database connection under the db key in a configuration file and fetch it with the Zend\Db\Adapter\Adapter key from the service manager - then the rest is done for you automatically.
EDIT:
Make sure that you have enabled the AdapterServiceFactory in your configuration for the above to work. Provided that you are using the ZendSkeletonApplication, add the below within config/autoload/global.php.
return array(
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
to config ( global.php etc ):
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=mydb;host=localhost',
'username' => 'mydb',
'password' => '',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
Go to diectory : you_application_folder/config/autoload/
in global.php
<?php
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=mydb;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
);
?>
in local.php // save important data here
<?php
return array(
'db' => array(
'username' => '*****',
'password' => '*****',
);
?>
Related
I am trying to connect the doctrine, but I do not quite understand how I can create entities from the console, so for example, to make it easier to create Many to Many
I have already connected the Doctrine itself:
//public/bootstrap/bootstrap.php
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'db.options' => array(// Подробнее настройка DBAL тут: http://silex.sensiolabs.org/doc/providers/doctrine.html
'driver' => 'pdo_mysql',
'dbname' => 'test',
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'password',
'charset' => 'utf8'
)
));
there is nothing in the official documentation on how to create entities - https://silex.symfony.com/doc/2.0/providers/doctrine.html
I could not find it on the Internet either, maybe someone knows how to cope with this?
I have 3 type of databases:
Authen DB (fixed address and fixed schema)
Config DB (fixed address and fixed schema)
Service DBs (dynamic address and dynamic schema based on each service)
After users logined and verified via Authen DB.
Based on the information store in Config DB, all actions in ZF2 application relate to the service should be done on the correlative Service DBs.
Does ZF2 support this case? How can I solve this?
Below codes are my global.php and local.php.
global.php
return array(
'db' => array(
// primary database
'driver' => 'Pdo',
'dsn' => 'mysql:host=xxx.xxx.xxx.xxx;dbname=db_authen',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
),
// other database
'adapters' => array(
'db_config' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:host=yyy.yyy.yyy.yyy;dbname=db_config',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
),
),
),
),
'service_manager' => array(
// primary database
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
'navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory'
),
// other database
'abstract_factories' => array(
'Zend\Db\Adapter\AdapterAbstractServiceFactory',
),
),
);
local.php
return array(
'db' => array(
// primary database
'username' => '*****',
'password' => '*****',
// other database
'adapters' => array(
'db_config' => array(
'username' => '*****',
'password' => '*****',
),
),
),
);
Thanks,
After you do your authentication against the (statically configured) Auth DB and consult the (statically configured) Config DB for the dynamic information you need for the Service DB, you could probably instantiate yourself the correct DB-adapter for the Service DB, using something like:
// Config from the Config DB, packaged into an array with keys that
// are expected by \Zend\Db\Adapter\Adapter
$config = [
'driver' => 'Pdo_Mysql', // for example
'user' => 'my-dynamically-obtained-user',
'password' => 'my-dynamically-obtained-password',
'database' => 'my-dynamically-obtained-db-name',
// etc
];
$adapter = new \Zend\Db\Adapter\Adapter($config);
// Now use the $adapter to build queries
$statement = $adapter->query('SELECT * FROM `mytable`');
$results = $statement->execute();
// iterate over the results, etc.
Alternatively, you could feed the $adapter into a model object you create that hides the db-specific query details from the consumer.
See ZF2 docs for \Zend\Db\Adapter\Adapter
I'm digging into ZF2, and I've run into some confusion on how to use Zend\Config with Zend\Db to manually set up a connection.
In different places in the manual, there are db configs in different formats.
This one shows a flat array as the config format:
https://packages.zendframework.com/docs/latest/manual/en/modules/zend.db.adapter.html
$adapter = new Zend\Db\Adapter\Adapter(array(
'driver' => 'Mysqli',
'database' => 'zend_db_example',
'username' => 'developer',
'password' => 'developer-password'
));
While this one shows a nested format:
https://packages.zendframework.com/docs/latest/manual/en/modules/zend.config.introduction.html
$configArray = array(
'database' => array(
'adapter' => 'pdo_mysql',
'params' => array(
'host' => 'db.example.com',
'username' => 'dbuser',
'password' => 'secret',
'dbname' => 'mydatabase'
)
)
);
What I expect to happen is that I can call for a new db adapter like so, but this throws exceptions:
$config = new Zend\Config\Config(
array(
'db' => array(
'adapter' => 'Mysqli',
'params' => array(
'host' => 'db.example.com',
'username' => 'dbuser',
'password' => 'secret',
'dbname' => 'mydatabase'
)
)
)
);
$adapter = new Zend\Db\Adapter\Adapter($config->db);
What I end up having to do is:
$config = new Zend\Config\Config(
array(
'db' => array(
'driver' => 'Mysqli',
'host' => 'db.example.com',
'username' => 'dbuser',
'password' => 'secret',
'database' => 'mydatabase'
)
)
);
$adapter = new Zend\Db\Adapter\Adapter($config->db->toArray());
Is there a better way of achieving what I'm trying to achieve without having to resort to the service manager?
Ignore the example from the Zend Config introduction page, that's just showing how to make a config object from a PHP array, the structure of the array isn't meant to show anything in particular.
Since you don't want to use the service manager, you need to pass the parameters to the adapter class in the structure it expects. It expects an array, a config object won't work. You've worked out what the structure of the array is, so that's what you need to use.
I think this page in the docs: http://framework.zend.com/manual/2.3/en/tutorials/tutorial.dbadapter.html (the "Basic setup" section) gives a better explanation of the service manager approach, which is how I'd do it in an MVC app at least.
when i try connecting to my sql server database from my zf2 application as shown below,
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'sqlsrv:dbname=album;hostname=192.168.0.20',
'username' => 'user',
'password' => 'pass',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
I get this error,
File:
/usr/local/zend/apache2/htdocs/zf2-tutorial/vendor/zendframework/zendframework/library/Zend/Db/Adapter/Driver/Pdo/Connection.php:289
Message:
Connect Error: could not find driver
Am i missing something here? Or rather this does not work at all on the linux oriented machines ?
Try taking out this line: "// PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''".
Your connection say you are trying to connect to MSSQL and not MySQL.
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'sqlsrv:dbname=album;hostname=192.168.0.20',
'username' => 'user',
'password' => 'pass',
'driver_options' => array(
// PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
I always prep it like this without trouble, using dist files to set the right connection params as you work through deployment:
local config file
'database' => array(
'connection' => array(
'mysql_master' => array(
'driver' => 'Pdo_Mysql',
'host' => 'host',
'dbname' => 'analytics',
'username' => 'user',
'password' => 'pass',
'charset' => 'UTF8',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
),
),
),
),
Then in my Module.php, I define such a factory (in the getServiceConfig array):
'Zend\Db\Adapter\Adapter' => function ($sm){
$config = $sm->get('config');
$dbParams = $config['database']['config']['mysql_master'];
$adapter = new \Zend\Db\Adapter\Adapter($dbParams);
return $adapter;
},
Hope this helps. If this doesn't work, something else is going on.. let me know, I can help.
Cheers.
Alex
The problem is that you don't have the necessary driver installed. I had the same problem with postgres, and this solved it for me:
apt-get install php5-pgsql
However, I am not 100% sure what driver must be installed to make Sql Server work. I did read that it's no longer supported. See this: PHP PDO to MS SQL Server on Ubuntu Server. In a nutshell, your best bet is to rather use:
sudo apt-get install php5-sybase
and then connection string:
"dblib:host=sever;dbname=dbname"
From what I gather, that should connect you to a Sql Server database, but again, I can't gaurantee this because I don't have a setup to test it with. Hope that helps...
I hope this helps you some... I'm currently following along to the Zend Framework 2 skeleton application guide. My database parameters needed to be passed in the following way:
'db' => array(
'driver' => 'SQLSRV',
'hostname' => 'SqlServerName',
'Database' => 'SqlDatabaseName',
'uid' => 'UsertoConnectwith',
'pwd' => 'Passwordofusertoconnectwith'
),
I need to add sql logging to work in native WebProfileBundle.
When I do one default connection in application config, I see the sql
queries in my log. But my application uses many connections to many db
servers, so I can't add all the possible connections to config file.
I create runtime connections, i.e.:
$config = array(
'user' => 'user1',
'password' => 'pass1',
'driver' => 'pdo_mysql',
'port' => 3306,
);
$conn = DriverManager::getConnection($config);
then I think, should be command something like this
$conn->getConfiguration()->getSQLLogger($someLoggerObject);
I've tried to solve this problem with DependencyInjection, took
DoctrineBundle as example. But have no luck.
Any help with live code or link to proper documentation would be great
I have this in my conf:
$config = new Configuration;
/** configuration stuff */
$config->setSQLLogger(MyLogger::getInstance());
$connectionOptions = array(
'driver' => 'pdo_mysql',
'user' => DB_USER,
'password' => DB_PASS,
'host' => DB_HOST,
'dbname' => DB_NAME,
'charset' => 'utf8',
'driverOptions' => array(
'charset' => 'utf8'
)
);
$em = EntityManager::create($connectionOptions, $config);
I use Zend + Doctrine2 and that is in my bootstrap, my logger is a singleton (thats why getInstance). I've never user DriverManager, but i hope this helps.