Hello I'm trying to make a simple configuration file for my app
my project folder is:
inside folder 'app'
-Config.php
inside root directory:
-index.php
-config.php
this is how config.php looks like:
<?php
return [
'db' => [
'hosts' => [
'local' => 'localhost',
'externo' => '1.1.1.1',
],
'name' => 'db-stats',
'user' => 'root',
'password' => 'root'
],
'mail' => [
'host' => 'smtp.gmail.com'
]
];
?>
Config.php is:
<?php
namespace Project\Helpers;
class Config
{
protected $data;
protected $default = null;
public function load($file){
$this->$data = require $file;
}
public function get($key, $default = null){
$this->$default = $default;
$segments = explode('.', $key);
$data = $this->$data;
foreach ($segments as $segment) {
if(isset($data[$segment])){
$data = $data[$segment];
}else{
$data = $this->$default;
break;
}
}
return $data;
}
public function exists($key){
return $this->get($key) !== $this->$default;
}
}
?>
and finally index.php:
<?php
use Project\Helpers\Config;
require 'app/Config.php';
$config = new Config;
$config->load('config.php');
echo $config->get('db.hosts.local');
?>
the thing is I'm getting this 2 errors when I run the page:
Notice: Undefined variable: data in
C:\xampp\htdocs\probar\app\Config.php on line 11
Fatal error: Cannot access empty property in
C:\xampp\htdocs\probar\app\Config.php on line 11
please help me what's is wrong with this???
$this->data = require $file; not $this->$data = require $file;.
And $this->default = $default; instead of $this->$default = $default;
Otherwise those would be variable variables.
<?php
namespace Project\Helpers;
class Config
{
protected $data;
protected $default = null;
public function load($file){
$this->data = require $file;
}
public function get($key, $default = null){
$this->default = $default;
$segments = explode('.', $key);
$data = $this->data;
foreach ($segments as $segment) {
if(isset($data[$segment])){
$data = $data[$segment];
}else{
$data = $this->default;
break;
}
}
return $data;
}
public function exists($key){
return $this->get($key) !== $this->default;
}
}
You have a synthax error in the class constructor. In PHP, when you access a member attribute with the -> operator, you don't have to use the $ modifier.
The correct code looks like this:
<?php
namespace Project\Helpers;
class Config
{
protected $data;
protected $default = null;
public function load($file){
$this->data = require $file;
}
public function get($key, $default = null){
$this->default = $default;
$segments = explode('.', $key);
$data = $this->data;
foreach ($segments as $segment) {
if(isset($data[$segment])){
$data = $data[$segment];
}else{
$data = $this->default;
break;
}
}
return $data;
}
public function exists($key){
return $this->get($key) !== $this->default;
}
}
Related
I Have this problem: I should get a variable declared in a class and use it into the same class but I don't receive error and it don't work. This is my code:
<?php
class internal {
protected $settings;
private $ctoken = '';
private $fparam = '';
private $token = '';
function __construct($ctoken, $fparam, $token){
$this->ctoken = $ctoken;
$this->fparam = $fparam;
$this->token = $token;
}
public function settings($settings = ['disable_web_page_preview' => 'false', 'parse_mode' => 'HTML', 'MySQL' => true, 'PostgreSQL' => true])
{
$this->settings = $settings;
echo 'Settings caricate!';
}
public function botAdmin($user_id = null)
{
if($user_id == NULL){
$user_id = $this->user_id;
}
if(in_array($user_id, $this->settings()['admins'])){
return true;
}else{
return false;
}
}
public function SecTest()
{
if($this->ctoken != $this->fparam or $this->token == NULL){
die("Security test: not passed, script killed.");
}else{
echo "Security test: OK. <br />";
echo json_encode($this->settings);
}
}
public function getSettings(){
return $this->settings;
}
}
I don't know what to do, I don't receive any error but if I call the method SecTest it print "null"
Before your _construct method define the variables that are specific to your class.
class internal {
private $ctoken = '';
private $fparam = '';
private $token = '';
function __construct($ctoken, $fparam, $token){
$this->ctoken = $ctoken;
$this->fparam = $fparam;
$this->token = $token;
}
Fixed, I was calling the method that echo the settings before declare the settings.
I don't know that much about php. I have 3 files in my project.
1st one is system.php, which hold the hole application logic.
here its code:
<?php
require "config/config_system.php";
$config = new Config;
$config-> load('config.php');
// this is way i want to change setting.
echo $config-> replace("db.host" , "replace value");
?>
2nd one is config_system.php, which holds the configuration logic.here its code:
<?php
class Config {
protected $data;
protected $informaton;
protected $default;
public function load($file) {
$this->data = require $file;
$this->informaton = require $file;
}
public function find($key, $default = null) {
$this->default = $default;
$segments = explode(".", $key);
$data = $this->data;
foreach ($segments as $segment) {
if (isset($data[$segment])) {
$data = $data[$segment];
} else {
$data = $this->default;
break;
}
}
return $data;
}
public function exists($key) {
return $this->find($key) !== $this->default;
}
// this is the function i am trying to make valide
public function replace($value) {
$arrayvalues = explode(".", $value);
$informaton = $this->informaton;
foreach ($arrayvalues as $arrayvalue) {
if (isset($informaton[$arrayvalue])) {
$informaton = $informaton[$arrayvalue];
}
}
return $arrayvalues;
}
}
?>
and 3rd one is config.php, which holds the configurations.
<?php
return [
"installation" => [
// this is the value I want to change via a function to true.
"create_db" => "false",
"create_table" => "false"
],
"db" => [
"host" => "localhost",
"user_name" => "root",
"password" => ""
]
];
?>
Now I want to change some setting via a function. How can I do it?
public function replace ($keyset, $value){
$key_parse = explode(".",keyset);
$this->data[$key_parse[0]][$key_parse[1]] = $value;
return $this->data;
}
Use this function in your config_system.php
I created a standart class Loadercontent(controller) in Codeigniter.
Also in the same file a add abstract Search class and child class SearchDoctor:
When I try to get CI instance &get_instance(); at abstract constructor, I get NULL:
$this->_ci =&get_instance();
var_dump($this->_ci); // NULL
So after I can not use:
$this->_ci->load->view($this->view, $this->item);
because $this->_ci is empty. What is wrong in my code ot abstract class in CI? Also maybe you can ask something about code? Is it wrong?
The full code:
<?php
abstract class Search
{
protected $fields = array('country' => 'country', 'city' => 'city');
protected $table;
protected $limit = 20;
protected $offset = 0;
protected $items;
protected $rand = false;
protected $data;
protected $view;
protected $_ci;
public function __construct($input)
{
$this->_ci =&get_instance();
$this->data = $input;
$this->getPostGet();
}
public function getPostGet(){
if(empty($this->data)){
foreach($this->data as $key => $val){
$this->_check($val, $key);
}
}
}
public function _check($val, $key){
if(in_array($val, $this->fields)){
$this->items[] = $this->getField($val, $key);
}
}
public function getField($value, $key){
return $key. ' = '.$value;
}
public function doQuery(){
if(!empty($this->items)){
$limit = $this->formatLimit();
$this->items = $this->other_model->getItemsTable($this->query, $this->table, $limit);
}
}
public function formatLimit(){
$this->offset = (isset($this->data['limit'])) ? $this->data['limit'] : $this->offset;
$this->limit = (isset($this->data['limit'])) ? $this->offset + $this->limit : $this->limit;
return array('offset' => $this->limit, 'limit' => $this->limit);
}
public function addFields($array){
$this->fields = array_merge($this->fields, $array);
}
public function getView(){
$this->_ci->load->view($this->view, $this->item);
}
public function response(){
echo json_encode($this->view); die();
}
}
class SearchDoctor extends Search
{
protected $fields = array('name' => 'DetailToUsersName');
public function __construct($type)
{
$this->table = 'users';
$this->view = 'users/doctors_list';
$this->limit = 10;
$this->rand = true;
$this->addFields($this->fields);
parent::__construct($type);
}
}
/* Init class */
class Loadercontent {
public function index(){
if(isset($_GET) || isset($_POST)){
$class = 'Search';
if(isset($_POST['type'])){
$type = $_POST['type'];
$input = $_POST;
}
if(isset($_GET['type'])){
$type = $_GET['type'];
$input = $_GET;
}
$class = $class.$type;
if (class_exists($class)) {
$obj = new $class($input);
$obj->getView();
$obj->response();
}
}
}
}
?>
I tried to follow the recommendations from this topic: zend framework 2 + routing database
I have a route class:
namespace Application\Router;
use Zend\Mvc\Router\Http\RouteInterface;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\Mvc\Router\RouteMatch;
class Content implements RouteInterface, ServiceLocatorAwareInterface {
protected $defaults = array();
protected $routerPluginManager = null;
public function __construct(array $defaults = array()) {
$this->defaults = $defaults;
}
public function setServiceLocator(\Zend\ServiceManager\ServiceLocatorInterface $routerPluginManager) {
$this->routerPluginManager = $routerPluginManager;
}
public function getServiceLocator() {
return $this->routerPluginManager;
}
public static function factory($options = array()) {
if ($options instanceof \Traversable) {
$options = ArrayUtils::iteratorToArray($options);
} elseif (!is_array($options)) {
throw new InvalidArgumentException(__METHOD__ . ' expects an array or Traversable set of options');
}
if (!isset($options['defaults'])) {
$options['defaults'] = array();
}
return new static($options['defaults']);
}
public function match(Request $request, $pathOffset = null) {
if (!method_exists($request, 'getUri')) {
return null;
}
$uri = $request->getUri();
$fullPath = $uri->getPath();
$path = substr($fullPath, $pathOffset);
$alias = trim($path, '/');
$options = $this->defaults;
$options = array_merge($options, array(
'path' => $alias
));
return new RouteMatch($options);
}
public function assemble(array $params = array(), array $options = array()) {
if (array_key_exists('path', $params)) {
return '/' . $params['path'];
}
return '/';
}
public function getAssembledParams() {
return array();
}
}
Pay attention that the match() function returns object of the instance of Zend\Mvc\Router\RouteMatch
However in the file Zend\Mvc\Router\Http\TreeRouteStack it checks for object to be the instance of RouteMatch (without prefix of namespace)
if (
($match = $route->match($request, $baseUrlLength, $options)) instanceof RouteMatch
&& ($pathLength === null || $match->getLength() === $pathLength)
)
And the condition fails in my case because of the namespace.
Any suggestions?
Ok, i figured out what the problem was.
Instead of returning Zend\Mvc\Router\RouteMatch I should return Zend\Mvc\Router\Http\RouteMatch
This fixed my problem
I keep getting the following exception with a new resource Im making and i cant figure out why:
PHP Fatal error: Uncaught exception 'Zend_Application_Bootstrap_Exception' with message 'Circular resource dependency detected' in /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php:656
Stack trace:
#0 /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php(623): Zend_Application_Bootstrap_BootstrapAbstract->_executeResource('modules')
#1 /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php(580): Zend_Application_Bootstrap_BootstrapAbstract->_bootstrap('modules')
#2 /Library/WebServer/Documents/doctrine-dev/library/APP/Doctrine/Application/Resource/Doctrine.php(36): Zend_Application_Bootstrap_BootstrapAbstract->bootstrap('modules')
#3 /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php(708): APP_Doctrine_Application_Resource_Doctrine->__construct(Array)
#4 /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php(349): Zend_Application_Bootstrap_BootstrapAbstract->_loadPluginResource('doctrine', Array)
#5 /opt/local/lib/php/Zend/Application/Bootstrap/Bootstra in /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php on line 656
As you'll see below ive created a Doctrine Resource that should load only in the general application bootstrap. In order to perform its tasks it needs the Modules resource to be bootstraped
so it calls $this->getBootstrap()->bootstrap('modules'). the Modules resoure never calls Doctrine though, and this seems to be where i get the circular dependency. Ive tried the code that is currently in the constructor for my Doctrine resource also as part of init directly and that doesnt seem to work either. An even bigger mystery to me though is that if i call $bootstrap->bootstrap('modules')
by itself before calling $bootstrap->bootstrap('doctrine') it all seems to play nicely. So why is there circular reference issue?
Relevant parts of application.xml
<resources>
<frontController>
<controllerDirectory><zf:const zf:name="APPLICATION_PATH" />/controllers</controllerDirectory>
<moduleDirectory><zf:const zf:name="APPLICATION_PATH" />/modules</moduleDirectory>
<moduleControllerDirectoryName value="controllers" />
</frontController>
<modules prefixModuleName="Mod" configFilename="module.xml">
<enabledModules>
<default />
<doctrinetest />
<cms>
<myOption value="Test Option Value" />
</cms>
<menu somevar="menu" />
<article somevar="article" />
</enabledModules>
</modules>
<doctrine>
<connections>
<default dsn="mysql://#####:######localhost/#####">
<attributes useNativeEnum="1" />
</default>
</connections>
<attributes>
<autoAccessorOverride value="1" />
<autoloadTableClasses value="1" />
<modelLoading value="MODEL_LOADING_PEAR" />
</attributes>
<directoryNames>
<sql value="data/sql" />
<fixtures value="data/fixtures" />
<migrations value="data/migrations" />
<yaml value="configs/schemas" />
<models value="models" />
</directoryNames>
</doctrine>
</resources>
Doctrine Resource
<?php
class APP_Doctrine_Application_Resource_Doctrine extends Zend_Application_Resource_ResourceAbstract
{
protected $_manager = null;
protected $_modules = array();
protected $_attributes = null;
protected $_connections = array();
protected $_defaultConnection = null;
protected $_directoryNames = null;
protected $_inflectors = array();
public function __construct($options = null)
{
parent::__construct($options);
$bootstrap = $this->getBootstrap();
$autoloader = $bootstrap->getApplication()->getAutoloader();
$autoloader->pushAutoloader(array('Doctrine_Core', 'autoload'), 'Doctrine');
spl_autoload_register(array('Doctrine_Core', 'modelsAutoload'));
$manager = $this->getManager();
$manager->setAttribute('bootstrap', $bootstrap);
// default module uses the application bootstrap unless overridden!
$modules = array('default' => $bootstrap);
if(!isset($options['useModules']) ||
(isset($options['useModules']) && (boolean) $options['useModules']))
{
$moduleBootstraps = $bootstrap->bootstrap('modules')->getResource('modules');
$modules = array_merge($modules, $moduleBootstraps->getArrayCopy());
}
$this->setModules($modules); // configure the modules
$this->_loadModels(); // load all the models for Doctrine
}
public function init()
{
return $this->getManager();
}
public function setConnections(array $connections)
{
$manager = $this->getManager();
foreach($connections as $name => $config)
{
if(isset($config['dsn']))
{
$conn = $manager->connection($config['dsn'], $name);
}
if(isset($config['attributes']) && isset($conn))
{
$this->setAttributes($config['attributes'], $conn);
}
}
return $this;
}
public function setAttributes(array $attributes, Doctrine_Configurable $object = null)
{
if($object === null)
{
$object = $this->getManager();
}
foreach($attributes as $name => $value)
{
$object->setAttribute(
$this->doctrineConstant($name, 'attr'),
$this->doctrineConstant($value)
);
}
return $this;
}
public function setModules(array $modules)
{
//$this->_modules = $modules;
foreach($modules as $name => $bootstrap)
{
$this->_modules[$name] = $this->_configureModuleOptions($bootstrap);
}
return $this;
}
public function setDirectoryNames(array $directoryNames)
{
$this->_directoryNames = $directoryNames;
return $this;
}
public function getDirectoryNames()
{
return $this->_directoryNames;
}
public function getDirectoryName($key)
{
if(isset($this->_directoryNames[$key]))
{
return $this->_directoryNames[$key];
}
return null;
}
public function getModuleOptions($module = null)
{
if($module === null)
{
return $this->_modules;
}
if(isset($this->_modules[$module]))
{
return $this->_modules[$module];
}
return null;
}
public function doctrineConstant($value, $prefix = '')
{
if($prefix !== '')
{
$prefix .= '_';
}
$const = $this->_getConstantInflector()->filter(array(
'prefix'=>$prefix,
'key' => $value
));
$const = constant($const);
return $const !== null ? $const : $value;
}
/**
* getManager
* #return Doctrine_Manager
*/
public function getManager()
{
if(!$this->_manager)
{
$this->_manager = Doctrine_Manager::getInstance();
}
return $this->_manager;
}
protected function _getConstantInflector()
{
if(!isset($this->_inflectors['constant']))
{
$callback = new Zend_Filter_Callback(array('callback'=>'ucfirst'));
$this->_inflectors['constant'] = new Zend_Filter_Inflector(
'Doctrine_Core::#prefix#key',
array(
':prefix' => array($callback, 'Word_CamelCaseToUnderscore', 'StringToUpper'),
':key' => array('Word_SeparatorToCamelCase', 'Word_CamelCaseToUnderscore', 'StringToUpper')
), null, '#');
}
return $this->_inflectors['constant'];
}
protected function _configureModuleOptions(Zend_Application_Bootstrap_BootstrapAbstract $bootstrap)
{
$coreBootstrapClass = get_class($this->getBootstrap());
if(get_class($bootstrap) === $coreBootstrapClass)
{
// handled differently
$resourceLoader = $bootstrap->bootstrap('DefaultAutoloader')->getResource('DefaultAutoloader');
$moduleName = $resourceLoader->getNamespace();
}
else
{
// handle a module bootstrap
$resourceLoader = $bootstrap->getResourceLoader();
$moduleName = $bootstrap->getModuleName();
}
$resourceTypes = $resourceLoader->getResourceTypes();
$modelResource = isset($resourceTypes['model'])
? $resourceTypes['model']
: array('path'=>'models', 'namespace'=>'Model');
$modulePath = $resourceLoader->getBasePath();
$classPrefix = $modelResource['namespace'];
$modelsPath = $modelResource['path'];
$doctrineOptions = array(
'generateBaseClasses'=>TRUE,
'generateTableClasses'=>TRUE,
'baseClassPrefix'=>'Base_',
'baseClassesDirectory'=> NULL,
'baseTableClassName'=>'Doctrine_Table',
'generateAccessors' => true,
'classPrefix'=>"{$classPrefix}_",
'classPrefixFiles'=>FALSE,
'pearStyle'=>TRUE,
'suffix'=>'.php',
'phpDocPackage'=> $moduleName,
'phpDocSubpackage'=>'Models',
);
$doctrineConfig = array(
'data_fixtures_path' => "$modulePath/{$this->getDirectoryName('fixtures')}",
'models_path' => "$modelsPath",
'migrations_path' => "$modulePath/{$this->getDirectoryName('migrations')}",
'yaml_schema_path' => "$modulePath/{$this->getDirectoryName('yaml')}",
'sql_path' => "$modulePath/{$this->getDirectoryName('sql')}",
'generate_models_options' => $doctrineOptions
);
return $doctrineConfig;
}
protected function _loadModels()
{
$moduleOptions = $this->getModuleOptions();
foreach($moduleOptions as $module => $options)
{
Doctrine_Core::loadModels(
$options['models_path'],
Doctrine_Core::MODEL_LOADING_PEAR,
$options['generate_models_options']['classPrefix']
);
}
return $this;
}
}
Modules Resource
<?php
class APP_Application_Resource_Modules extends Zend_Application_Resource_Modules
{
protected $_prefixModuleNames = false;
protected $_moduleNamePrefix = null;
protected $_defaultModulePrefix = 'Mod';
protected $_configFileName = 'module.xml';
protected $_enabledModules = null;
public function __construct($options = null)
{
if(isset($options['prefixModuleName']))
{
if(($prefix = APP_Toolkit::literalize($options['prefixModuleName']))
!== false)
{
$this->_prefixModuleNames = true;
$this->_moduleNamePrefix = is_string($prefix)
? $prefix
: $this->_defaultModulePrefix;
}
}
if(isset($options['configFileName']))
{
$this->_configFileName = $options['configFileName'];
}
parent::__construct($options);
}
protected function _mergeModuleConfigs(array $applicationConfig)
{
$cacheManager = $this->_getCacheManager();
if(isset($applicationConfig['resources']['modules']['enabledModules']))
{
$applicationModulesOptions = &$applicationConfig['resources']['modules'];
$enabledModules = &$applicationModulesOptions['enabledModules'];
$front = $this->getBootstrap()->getResource('frontcontroller');
foreach($enabledModules as $moduleName => $moduleOptions)
{
// cache testing
// note cache keys for modules are prefixed if prefix is enabled #see _formatModuleName
if(!$cacheManager->test('config', $this->_formatModuleName($moduleName)))
{
$configPath = $front->getModuleDirectory($moduleName).'/configs/'.$this->getConfigFilename();
if(file_exists($configPath))
{
if(strpos($configPath, ".xml") === false)
{
throw new Exception(__CLASS__." is only compatible with XML configuration files.");
}
$config = new Zend_Config_Xml($configPath);
$enabledModules[$moduleName] = array_merge((array) $moduleOptions, $config->toArray());
//$this->setOptions($options);
$cacheManager->save('config', $enabledModules[$moduleName], $this->_formatModuleName($moduleName));
}
}
else
{
$options = $cacheManager->load('config', $this->_formatModuleName($moduleName));
$enabledModules[$moduleName] = array_merge((array) $enabledModules[$moduleName], $options);
}
}
}
return $applicationConfig;
}
public function init()
{
/**
* #var Zend_Application_Bootstrap_BoostrapAbstract
*/
$bootstrap = $this->getBootstrap();
if(!$bootstrap->hasResource('frontController'))
{
$bootstrap->bootstrap('frontController');
}
$front = $bootstrap->getResource('frontController');
$applicationConfig = $this->_mergeModuleConfigs($bootstrap->getOptions());
$bootstrap->setOptions($applicationConfig);
parent::init();
return $this->_bootstraps;
}
/**
* Format a module name to the module class prefix
*
* #param string $name
* #return string
*/
protected function _formatModuleName($name)
{
$name = strtolower($name);
$name = str_replace(array('-', '.'), ' ', $name);
$name = ucwords($name);
$name = str_replace(' ', '', $name);
$options = $this->getOptions();
if($this->prefixEnabled())
{
$name = $this->getModuleNamePrefix().$name;
}
return $name;
}
protected function _getCacheManager()
{
$bootstrap = $this->getBootstrap();
if(!$bootstrap->hasResource('cacheManager'))
{
$bootstrap->bootstrap('cacheManager');
}
return $bootstrap->getResource('cacheManager');
}
public function prefixEnabled()
{
return $this->_prefixModuleNames;
}
public function getModuleNamePrefix()
{
return $this->_moduleNamePrefix;
}
public function getConfigFilename()
{
return $this->_configFileName;
}
public function setEnabledModules($modules)
{
$this->_enabledModules = (array) $modules;
}
public function getEnabledModules($controllerDirectories = null)
{
if($controllerDirectories instanceof Zend_Controller_Front)
{
$controllerDirectories = $controllerDirectories->getControllerDirectory();
}
if(is_array($controllerDirectories))
{
$options = $this->getOptions();
$enabledModules = isset($options['enabledModules'])
? (array) $options['enabledModules']
: array();
$this->_enabledModules = array_intersect_key($controllerDirectories, $enabledModules);
}
elseif(null !== $controllerDirectories)
{
throw new InvalidArgumentException('Argument must be an instance of
Zend_Controller_Front or an array mathing the format of the
return value of Zend_Controller_Front::getControllerDirectory().'
);
}
return $this->_enabledModules;
}
public function setPrefixModuleName($value)
{
$this->_prefixModuleNames = APP_Toolkit::literalize($value);
}
}
Module Bootstrap Base Class
<?php
class APP_Application_Module_Bootstrap extends Zend_Application_Module_Bootstrap
{
public function _initResourceLoader()
{
$loader = $this->getResourceLoader();
$loader->addResourceType('actionhelper', 'helpers', 'Action_Helper');
}
}
Maybe this section of the e-book "Survive the Deep End" might help you : 6.6. Step 5: Fixing ZFExt_Bootstrap -- it specifically speaks about the error you are getting.
(I won't quote as there is quite a couple of long paragraphs, but, hopefully, this'll help)