replace string value in config.php - php

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

Related

Cannot use [] for reading when including

I have this PHP file:
<?php
namespace FrameWork\Controller;
abstract class ControllerBase
{
protected $action;
protected $vars;
public function __construct($action, $vars = NULL)
{
$this->action = $action;
$this->vars = $vars;
$this->populateVars();
}
public function run()
{
****BETWEEN HERE****
$r = new \ReflectionMethod($this, $this->action);
$params = $r->getParameters();
$funcParams[];
foreach($params as $param)
{
$paramName = $param->getName();
$funcParams[$paramName] = $this->vars[$paramName];
}
****AND HERE****
call_user_func_array(array($this, $this->action), $funcParams);
}
private function PopulateVars()
{
foreach($_GET as $key => $getVar)
{
$this->vars[$key] = $getVar;
}
foreach($_POST as $key => $postVar)
{
$this->vars[$key] = $postVar;
}
}
}
It is includeed in another file, and for some reason I am getting an exception thrown on the include.
Cannot use [] for reading
When I remove everything between ****BETWEEN HERE**** and ****AND HERE****, it works (or at least doesn't throw the same exception).
Any idea what's going on?
Have you tried replacing
$funcParams[];
with
$funcParams = array();
I think it will solve your problem.

PHP function to get url from route

I have this class:
class Route
{
protected $routes = [
"view_article" => "view/{articleUrl}",
"edit_article" => "edit/{articleId}"
];
}
How can I make a function that returns the url replacing content inside brackets?
For example if I use this code:
$route->getUrl('view_article', 'first-article');
It should return: view/first-article
Then you should make a function that return your variable?
class Route {
function getUrl($find, $replace) {
$entry = isset($this->routes[$find]) ? $this->routes[$find]: false;
if($entry) {
return str_replace(sprintf('{%s}', $find), $replace, $entry);
} else {
return return false;
}
}
}
something like that.
function getUrl($key, $value){
$value = preg_replace('/[\[{\(].*[\]}\)]/U' , $value, $this->routes[$key]);
return $value;
}
A couple of solutions here:
getUrl below will accept the route name as the first parameter, then replace any placeholders with the subsequent variables. Not the best solution - you may have too many or too few variables. When using IDEs, there will be no parameter hinting.
class Route
{
protected $routes = [
"view_article" => "view/{articleUrl}",
"edit_article" => "edit/{articleId}",
"view_page" => "view/{articleId}/{pageName}"
];
public function getUrl() {
$arg_list = func_get_args();
$route = $this->routes[$arg_list[0]];
unset($arg_list[0]);
foreach($arg_list as $arg) {
$route = preg_replace('/{[^\}]+}/', $arg, $route, 1);
}
return $route;
}
}
$route = new Route();
var_dump($route->getUrl('view_page', '17', 'hello_world')); //'view/17/hello_world'
An alternative approach is to use an array of arguments and str_replace the key=>value pairs:
class Route
{
protected $routes = [
"view_article" => "view/{articleUrl}",
"edit_article" => "edit/{articleId}",
"view_page" => "view/{articleId}/{pageName}"
];
public function getUrl($routeName, $args) {
$route = $this->routes[$routeName];
foreach($args as $key => $value) {
$route = str_replace(sprintf('{%s}', $key), $value, $route);
}
return $route;
}
}
$route = new Route();
var_dump($route->getUrl('view_page', ['articleId' => 17, 'pageName' => 'hello_world'])); //'view/17/hello_world'
In both cases, be sure to include additional checks (route exists, all the variables have been replaced, etc).

Error with this PHP config file

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;
}
}

zend framework 2 + custom routing

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

Calling Method of array of objects?

How can I call methods from an array of objects (that hold an array of objects). I read: Get array with results of object method on each item in an array of objects in PHP but could not get it.
Here is my testcode: the first object holds attributes, then an object holds a record of the multiple attributes.
/*--------------------------------- */
class SqliteAttribute {
private $_fieldname = '';
private $_fieldvalue = '';
private $_type = 'TEXT';
private $_key = true;
function __construct($fieldname, $fieldvalue, $text, $key) {
$this->_fieldname = $fieldname;
$this->_fieldvalue = $fieldvalue;
$this->_text = $text;
$this->_key = $key;
}
function AsArray() {
$tempArray = array('fieldname' => $this->_fieldname,
'fieldvalue' => $this->_fieldvalue,
'type' => $this->_type,
'key' => $this->_key
);
return $tempArray;
}
}
/*--------------------------------- */
class SqliteRecord {
private $_attributes = array();
function __construct() {
}
function AddAttribute($fieldname, $fieldvalue, $text, $key) {
$attribute = new SqliteAttribute($fieldname, $fieldvalue, $text, $key);
$this->attributes[] = $attribute;
var_dump($this->_attributes); // shows it!
}
function AsArray() {
$temp_array = array();
var_dump($this->_attributes); // shows nothing
foreach ($this->_attributes as $key => $value) {
$temp_array[] = $value->AsArray();
}
return $temp_array;
}
}
And I call it like this
function updateFiles($files, $rootpath) {
$recordset = new SqliteRecordSet;
foreach ($files as $file) {
$record = new SqliteRecord;
$record->AddAttribute('Path', $file[0], 'TEXT', true);
print_r($record->AsArray()); // shows nothing
}
$recordset->insertIfNotExist_index();
}
$this->attributes vs $this->_attributes
you should always develop code with error reporting set to E_ALL and display_errors on. php would have notified you of your mistake here.

Categories