How to access %APPDATA% in laravel - php

I have electron application which contains laravel project, I want to create a sqlite database on booting and store it in AppData Folder. Then from database.php in config folder, I want to access AppData Folder and get the database. Everything works fine in terms of creating the database on booting, but I can't access AppData Folder in laravel. It throws an error.
This is my code for creating database on booting in AppServiceProvider
public function boot()
{
if(!file_exists('%APPDATA%\pos\database.sqlite')){
//1. create the file
$handle = fopen('%APPDATA%\pos\database.sqlite', 'w') or die('Cannot open file');
Artisan::call('migrate');
fclose($handle);
}
Schema::defaultStringLength(191);
Blade::directive('active', function ($url) {
return "<?php echo request()->is($url.'*') || request()->is($url.'/*')? ' active' : ''; ?>";
});
}
And here is my sqlite code from database.php
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => '%APPDATA%\pos\database.sqlite',
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
What should I do ? is there any alternative solutions for retrieving the database in electron ?

APPDATA is an environment variable. You can use Laravel's env() helper function to access it.
$appdata = env('APPDATA');
Make sure you have a sensible backup plan for when the APPDATA environment variable doesn't exist.

Related

yii2 jasper on basic template

I've followed step by step instructions from JasperReports for yii2.
Installed JDK 1.8 on my Debian 8
Setted up mysql connector's classpath in /etc/profile
Added chrmorandi/yii2-jasper to my composer and updated
I guess php exec() function is enabled because the following test in any view resolves successfuly ...
<? echo exec('whoami'); ?>
chromandi is now under /vendors
java -version says 1.8.0_111
$CLASHPATH points to /usr/share/mysql-connector-java/mysql-connector-java-5.1.40-bin.jar
configuration is so ...
'components' => [
'jasper' => [
'class' => 'chrmorandi\jasper',
'db' => [
'host' => 'localhost',
'port' => 3306,
'driver' => 'mysql',
'dbname' => 'acme',
'username' => 'acme',
'password' => 'acme'
]
],
...
]
I added a controller like this ...
<?php
namespace app\controllers;
use Yii;
use chrmorandi\Jasper;
class EstadisticasController extends \yii\web\Controller {
public function actionIndex() {
// Set alias for sample directory
Yii::setAlias('example', '#vendor/chrmorandi/yii2-jasper/examples');
/* #var $jasper Jasper */
$jasper = Yii::$app->jasper;
// Compile a JRXML to Jasper
$jasper->compile(Yii::getAlias('#example') . '/hello_world.jrxml')->execute();
// Process a Jasper file to PDF and RTF (you can use directly the .jrxml)
$jasper->process(Yii::getAlias('#example') . '/hello_world.jasper', [
'php_version' => 'xxx'
], [
'pdf',
'rtf'
], false, false)->execute();
// List the parameters from a Jasper file.
$array = $jasper->listParameters(Yii::getAlias('#example') . '/hello_world.jasper')->execute();
// return pdf file
Yii::$app->response->sendFile(Yii::getAlias('#example') . '/hello_world.pdf');
}
}
and tested http://www.acme.es/estadisticas/index that is supposed to be a built-in example.
Now it comes the problem. It complains about
$jasper = Yii::$app->jasper;
line. The output says
ReflectionException Class chrmorandi\jasper does not exist
Anyone facing this issue? There is no much info about jasper on Yii. Any help would be welcome.
Thank you.
Finally the solution was changing
$jasper = Yii::$app->jasper;
to
$jasper = new \chrmorandi\jasper\Jasper();
Don't know why in the yii2-jasper documentation is setted so if it does not work. Anyway you can make it work following my above compilation.
As the
use chrmorandi\Jasper
is not working properly
You will have to change Jasper.php setting in the init function this
$componentes = Yii::$app->components;
$this->db = $componentes['jasper']['db'];
to make it work.
Editing under vendors is not something I want to do. In order to prevent these fixes I moved from chrmorandi's extension (until its improvement) to cossou/jasperphp extension.
So far the cossou's extension reaches all my goals.
I hope this helps somebody.

CakePHP with Sqlite3: How to connect to multiple sqlite file?

I working on a project where user register and get a free online shop using CakePHP v2.6.5. I'm using shared hosting so i can't create Mysql database for them, So I use sqlite instead. Because I need to use it with Mobile App too. In my code I dynamically create sqlite file for user after their register. But I don't know how to change database path in CakePHP. All I know is CakePHP use config in config/database.php file, but i can't init it dynamically.
In my config/database.php file:
public $sqliteDB = array(
'datasource' => 'Database/Sqlite',
'persistent' => false,
//'database'=>'',
'prefix' => '',
'encoding' => 'utf8'
);
I trying to follow these link:
CakePHP switch database (using same datasource) on the fly?
and this link
Cakephp can't change database on-the-fly, but I got nothing.
I figure out how to do it by create ConnectionManager on the fly in __construct() method of model. But I use it with multi table so here my code
In AppModel:
public function connectSqlite()
{
App::uses('CakeSession', 'Model/Datasource');
$shop = CakeSession::read('SHOP'); //just read Session for shop's name, because i create a directory and store sqlite in it. Directory name base on shop name that user defined when user registerd.
if($shop)
{
$dbName=FILES_URL.'shops'.DS.$shop['name'].DS.'database'.DS.'database.sqlite'; //Sqlite file path
$sqliteDB = array(
// Set correct database name
'datasource' => 'Database/Sqlite',
'persistent' => false,
'database'=>$dbName,
'prefix' => '',
'encoding' => 'utf8'
);
// Add new config to registry
ConnectionManager::create($dbName, $sqliteDB); //create ConnectionManager and return it to derived class.
// Point model to new config
return $dbName;
}
}
In Product Model:
public function __construct($id = false, $table = null, $ds = null)
{
$dbName=parent::connectSqlite();
if($dbName){
$this->useDbConfig=$dbName;
}
parent::__construct($id, $table, $ds);
}
Hope this can help!

in Zend instead of application.ini, can i have my configuration store in php file like config.php

I am working on a project based on Zend 1.12. There is a new requirement in which we have to encode all of our files to prevent hacking. We used ioncube encoder which encode all of the .php file but not application.ini where it store db information username, password, secret key etc. There are two approach :
1) Have configuration reside in .php file such as config.php instead of application.ini
2) have ioncube encode application.ini
With the first approach I found Zend Config Introduction where you could have configuration store in array. I need a concrete example with setup in Bootstrap.php where it could utilize these configuration. Right now all of our model extends from Zend_Db_Table_Abstract. I really want when i migrate all the application.ini db configuration into config.php all the db operation works and there are several instance in front controller make use of $this->applicationOptions. I hope my putting configuration this will work as well. Please help
With second approach I did not found much resolution on ioncube be able to encode application.ini
This is my configuration file
return $configArray = array(
'db' => array(
'adapter' => 'pdo_mysql',
'params' => array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'test'
)
)
);
When i do this in Bootstrap.php and it work
$config = new Zend_Config(require APPLICATION_PATH .'/configs/config.php');
$db = Zend_Db::factory($config->db->adapter,
$config->dv->params->toArray());
$db = Zend_Db::factory($config->db);
Zend_Db_Table::setDefaultAdapter($db);
but when i do
protected function _initDatabase(){
$config = new Zend_Config(require APPLICATION_PATH .'/configs/config.php');
$resource = $this->getPluginResource('db');
var_dump($this->getPluginResource('db')); // this will be null.
My question is is should i do anything different in configuration so it will mimic resources.db.adapter, resources.db.params.host etc and it will be picking up by the pluginResources or getoptions
Normally it is expected that users would use one of the adapter classes such as Zend_Config_Ini or Zend_Config_Xml, but if configuration data are available in a PHP array, one may simply pass the data to the Zend_Config constructor in order to utilize a simple object-oriented interface.
Basically, you first create a PHP file that contains the configuration :
// config.php
return array(
...
...
);
And, then, from another file, use than configuration file :
$config = new Zend_Config(require 'config.php');
In your Bootstrap.php try getting the configuration like this
protected function _initDb()
{
$resource = $bootstrap->getPluginResource('db');
$db = $resource->getDbAdapter();
Zend_Registry::set("db", $db);
}
After registering the db variable in your Bootstrap.php you can access it like this
$dbAdapter = Zend_Registry::get("db");
You use getPluginResource() hence you need to have your configuration keys in the following way:
resources.db.adapter = ...
resources.db.params.host = ...
...
or your config.php should look like this:
// config.php
return array(
'resources' => array(
'db' => array(
...
),
),
...
);
This page could be helpful.

Cakephp 2 multiple DBs

I want to switch DB based on domain, selecting credentials from another DB, but I can't switch..
AppController.php
// Select username, password and database based on domain
$this->Company->find('first', [...]);
if ($company) {
// Connect to second database, droping connection from first.
$dataSource = ConnectionManager::getDataSource('default');
$dataSource->config['login'] = $company['Company']['dbuser'];
$dataSource->config['password'] = $company['Company']['dbpass'];
$dataSource->config['database'] = $company['Company']['dbname'];
/**
* PROBLEM START HERE:
* Here, need to use new database settings, and, this case
* Company table does not exists, but I always get it, so,
* I think I am connected with the first and not second connection.
*/
print_r($this->Company->find('first'));
}
How I can correct this?
EDIT
I have tried without success:
ConnectionManager::drop('default');
ConnectionManager::create('default', $settings);
A print_r(ConnectionManager::create('default', $settings)) return:
[... lots of things ... ]
[config] => Array
(
[persistent] =>
[host] => localhost
[login] => login
[password] => password
[database] => database
[port] => 3306
[datasource] => Database/Mysql
[prefix] =>
)
[... more things ... ]
EDIT 2
Now, I can switch database, but, Company Model always get the old database settings.
FooController.php
<?php
App::uses('AppController', 'Controller');
class FooController extends AppController {
var $uses = array('Foo', 'Company');
public function index() {
echo'<pre>';
print_r($this->Company->find('first')); // Here I get from old settings
print_r($this->Foo->find('first')); // Here I gete from new settings
echo'</pre>';
$this->layout = false;
$this->render(false);
}
}
AppController.php
public function beforeFilter() {
$company = ClassRegistry::init('Company')->find('first');
$settings = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => $company['Company']['dbuser'],
'password' => $company['Company']['dbpass'],
'database' => $company['Company']['dbname'],
'prefix' => ''
);
ConnectionManager::getDataSource('default')->disconnect();
ConnectionManager::drop('default');
ConnectionManager::create('default', $settings);
ConnectionManager::getDataSource('default')->connect();
}
It looks like you need to dynamically create a config and change configs on-the-fly. I don't know if this will work, but it may lead you to the answer.
First we need to create a config for the datasource to use. For this we can use ConnectionManager::create
Next, we need to change configs on-the-fly and for that we can use Model::setDataSource
I haven't tried, but it looks like it should do. If there are issues, leave a comment so I can update the answer.
Edit: This may not work since every model would need to change the to the new datasource. There is a ConnectionManager::drop() method that you could use to drop the default config and then ConnectionManager::create('default', array(...)); to use a new default perhaps.
You can switch databases in your database config file.
Configure your Config/database.php file as follows:
<?php
class DATABASE_CONFIG {
// config for e.g. localhost
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'xxxxx',
'database' => 'cake',
'encoding' => 'utf8'
);
// DB config specifically for your domain
public $domain_x = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'username_at_hosting_provider',
'password' => '087bJ#ytvh&^YU#T',
'database' => 'blabla_cake',
'encoding' => 'utf8'
);
public function __construct(){
// switch config depending on domain / env('HTTP_HOST')
if(env('HTTP_HOST')=='domain_x.com'){
$this->default = $this->domain_x;
}
// otherwise keep $this->default
}
}
Edit:
It seems a was a bit too fast answering your question: it does not really cover your question. Sorry!
Okay, so I managed to fix this problem creating the __construct function whithin AppModel and put all the code to drop the default datasource and create another with the new config. Something like this:
AppModel.php
public function __construct($id = false, $table = null, $ds = null)
{
App::uses('CakeSession', 'Model/Datasource');
parent::__construct($id, $table, $ds);
if ($this->useDbConfig == 'default') {
// Change the datasource config
$user = CakeSession::read('Auth.User');
$this->changeDataSource($user);
}
}
public function changeDataSource($config)
{
...
...
...
$dados = array();
$dados['database'] = $config['titulo_bd'];
$dados['host'] = $config['host_bd'];
$dados['login'] = $config['login_bd'];
$dados['password'] = $config['senha_bd'];
$dados['datasource'] = 'Database/Mysql';
$dados['persistent'] = false;
$dados['prefix'] = '';
$dados['encoding'] = 'utf8';
ConnectionManager::create('default', $dados);
ConnectionManager::getDataSource('default')->connect();
}
My case is very similar. In my case, I have two types of connections. One is the default core connection which uses the Config/database.php file for connection configurations. Second one is a dynamic configuration which uses db details saved for logged in user. So, for a few specific actions I have to switch between the default db connection and user based db connection. Here's how it came up.
To switch to user based db connection from default file
try {
ConnectionManager::getDataSource('default')->disconnect();
ConnectionManager::drop('default');
ConnectionManager::create('default', $this->config);
ConnectionManager::getDataSource('default')->connect();
$db = ConnectionManager::getDataSource('default');
} catch (MissingDatabaseException $e) {
$this->Session->setFlash($e->getMessage());
}
where $this->config is user based connection.
To switch back to default file based connection I do:
try {
ConnectionManager::getDataSource('default')->disconnect();
ConnectionManager::drop('default');
$dbconfig = new DATABASE_CONFIG();
ConnectionManager::create('default', $dbconfig->default);
ConnectionManager::getDataSource('default')->connect();
$db = ConnectionManager::getDataSource('default');
}
where $dbconfig->default i.e. $default contains my default connection configuration in Config/database.php

How to specify database configuration in CakePHP 2.0.2?

I've just installed CakePHP 2.0.2 for use in a new project. I'm trying to use a database configuration called development but my model doesn't seem to be picking it up.
Based on CakePHP 2's new directory and file name conventions, I've created the following at /app/Model/AppModel.php:
<?php
class AppModel extends Model {
public $useDbConfig = 'development';
}
However, the default home page tells me:
Cake is NOT able to connect to the database.
Yet if I change the configuration name in /app/Config/database.php to default the message changes to a success message, as though it's not picking up my custom AppModel class.
How can I remedy this? As the new CakePHP 2.0 docs say to use the $useDbConfig property as I have done above?
EDIT: Contents of /app/Config/database.php:
class DATABASE_CONFIG {
public $development = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'cakephp_db',
'prefix' => '',
'encoding' => 'utf8',
);
}
Like dhofstet has explained, you still need to have a default config. What I do is add a constructor to the DATABASE_CONFIG class to switch between database configs.
Something like this...
public function __construct()
{
if (DEV_SERVER) {
$this->default = $this->development;
} else {
$this->default = $this->production;
}
}
Your database configuration is very likely correct.
The reason "Cake is NOT able to connect to the database." is shown, is because the script that checks whether it can connect to the database (/lib/Cake/View/Pages/home.ctp) only uses the default database connection for this test. And as there is no such connection, it fails.

Categories