PHP extends namespace\class unknown error - php

This is my parent class code: \core\controller\controlmaster
<?php
namespace core\controller;
class controlmaster{
private $model_base = null;
//public function __construct(){
//always start session for any loaded controller
//session_start();
//}
public function _loadModels($models){
$file = dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR.$this->model_base.$models.".php";
$file_alloc = str_replace("\\","/",$file);
if(file_exists($file_alloc)){
require($file_alloc);
$models_name = $this->model_base.$models;
return new $models_name();
}
}
public static function _setModelBase($model_location){
$this->model_base = $model_location;
}
}
?>
and this is my controller page for application : \applications\controller\index
<?php
namespace applications\controllers;
use core\configuration\configloader as config;
class index extends \core\controller\controlmaster{
public $config;
public function __construct(){
$this->config = new config;
$this->config->_parsePHP("j3mp_setting.php");
parent::_setModelBase($this->config->settings['app_model_base']); // Error doesn't appear when i comment this function
echo "This is main page and this is config for model app base : {$this->config->settings['base_url']}";
}
}
?>
This is core\configuration\configloader:
<?php
namespace core\configuration;
class configloader{
//Contains setting informations
public $inisettings;
public $settings;
public function _parseINI($file,$section){
$section = empty($section) ? false : true;
$file = __DIR__.DIRECTORY_SEPARATOR.$file;
if(file_exists($file)){
$parse = parse_ini_file($file,$section);
$this->inisettings = $parse;
}else{
throw new core\errorhandler\exception("File {$file} is not found in our system. Please contact administrator for details.","configloader");
}
}
public function _parsePHP($file){
$file = __DIR__.DIRECTORY_SEPARATOR.$file;
if(file_exists($file)){
$settings = array();
include($file);
$this->settings = $settings;
}else{
throw new core\errorhandler\exception("File {$file} is not found in our system. Please contact administrator for details.","configloader");
}
}
}
?>
When i comment "parent::_setModelBase(...)" code, the error disappear and the browser successfully print "This is main page and this is config for model app base : http://iosv3.net/". I think the error come from \core\controller\controlmaster, but I don't know how to fix that? I always try to edit the file (\core\controller\controlmaster) but notting happens... If error occured, the message ("This is main page ...") doesn't come out... Could you show me where is the error come from? Thanks...

Related

How to use namespace properly in PHP?

I have this file root/core/Router.php
<?php
namespace Core;
class Router {
protected $url;
protected $controller;
private function parseURL() {
// threat the $this->url; for example ["r", "product"]
}
private function request() {
$this->controller = Controller::get($this->url[1]);
}
public function __construct() {
$this->parseURL();
$this->request();
}
}
?>
then file root/core/Controller.php
<?php
namespace Core;
class Controller {
public static function model($name, $params = []) {
$model = "\\Model\\$name";
return new $model($params);
}
public static function view($name, $params = []) {
require_once APP_DIR . "view/" . $name . ".php";
}
public static function get($name, $params = []) {
require_once APP_DIR . "controller/" . $name . ".php";
$name = "\\Controller\\$name";
return new $name($params);
}
}
?>
then root/controler/Product.php
<?php
namespace Controller;
use Core\Controller;
use Model\Product;
class Product {
public function get() {
$ret['state'] = 510;
$productModel = new Product;
$products = $productModel->getAll();
if(isset($products)) {
$ret['products'] = $products;
$ret['state'] = 200;
}
return $ret;
}
}
?>
then file root/model/Product.php
<?php
namespace Model;
class Product {
public function add($values) {
return Database::insert("product", $values);
}
}
?>
and root/core/Model.php
<?php
namespace Core;
class Model {
protected $table = null;
public function getAll() {
// some code to collect data
}
}
?>
What i want to achive is that every Controller in root/controller/*.php able to load any Model in root/model/*.php but class inside root/model/*.php must able to access (inheritance/extends) the Model class inside root/core/Model.php i firstly asked on chatGPT for some AI Generated answer, that the reason why i get this far.
Then i get this error, when the AI keep giving the same answer.
Fatal error: Cannot declare class Controller\Product because the name is already in use in C:\xampp\htdocs\app\shop\controller\Product.php on line 6
I actually realize that the simple way probably with naming the class so ther no conflict between it but i became aware how to properly using the namespace if its such features in php. Those files loaded without any autoloader, so i just require_once each file in root/init.php file.
I read few documentations but hard to implement in multiple files and directorys.
I Apreciate any feedback, thanks

Set static variable from config's file in PHP

I have a simple PHP-static-class that writes in log.txt the log of my script.
It is:
<?php
class Log {
$fileLogConfig = ''; //include 'config.inc'; -> it's an error!
//Write the log in log.txt
public static function tracciaOperazioniNelLog($operation) {
$fileLog = fopen($fileLogConfig['log'], "a+") or die("Error! \n");
fwrite($fileLog, $operation . "\n");
fclose($fileLog);
}
}
?>
The $fileLogConfig is a variable that receives "log"'s param from config.inc.
This is my file config.inc:
<?php
return array(
...,
'log' => 'log.txt',
...
);
?>
But PHP says error about include 'config.inc'? Where is my error(s)?
Thanks!
You need to include the file in a constructor.
<?php
class Log {
public $fileLogConfig;
function __construct(){
$this->fileLogConfig = include 'config.inc.php';
}
}
$o = new Log();
print_r($o->fileLogConfig);
UPDATE
I overlooked that OP has a static class.
So, create an initialize() method to set your static variables.
class Log {
public static $fileLogConfig;
public static function initialize(){
self::$fileLogConfig = include 'config.inc.php';
}
}
Log::initialize();
print_r(Log::$fileLogConfig);

Interface 'mylogginginterface' not found in dblogger.php file

Please help me to find solution is that did code already. but when i run the program it's say Interface 'mylogginginterface' not found in dblogger.php file. i am confused where i am wrong. please check my code.
Check these files please.
Index.php file
<?php
include_once("classes/dblogger.php");
include_once("classes/loggerinterface.php");
$logging = new dbloggingsystem();
$profile = new userprofile($logging);
echo $profile->createuser();
?>
loggerinterface.php file
<?php
interface mylogginginterface {
public function log($message);
}
?>
dblogger.php file
<?php
/** **/
class dbloggingsystem implements mylogginginterface
{
public function log($message) {
echo "Logging message of user is:- $message";
}
}
userprofile.php
<?php
class userprofile
{
private $fullloggingsystem;
public function createuser() {
$this->fullloggingsystem->log("user created");
}
public function updateuser() {
$this->fullloggingsystem->log("user update");
}
public function deleteuser() {
$this->fullloggingsystem->log("user deleted");
}
public function __construct(mylogginginterface $myloggingsystem){
$this->fullloggingsystem = $myloggingsystem;
}
}
Please check it where i am wrong and why this error occur. thanks in advance.
you just need to include your loggerinterface file first then dblogger.php
inlcude_once ("loggerinterface.php");
inlcude_once ("dblogger.php");

Deal with AJAX block in web-crawler or create manually inputs

Based on Alvin Bunk article link to article I want to create a web-cralwer that logins in a website then submits a form.
My problem is that on that website there is an Ajax block that generates after clicking and empty link few inputs that I need to fill so I need to click that empty link somehow or to insert the inputs manually .
I changed the code below in a lot of ways to try to make it work but on the visit function I got stuck
I get Uncaught Error: Call to a member function visit() on null
<?php
require 'vendor/autoload.php';
trait MinkSetup
{
private $minkBaseUrl;
private $minkSession;
/**
* #before
*/
public function setupMinkSession()
{
$this->minkBaseUrl = 'https://www.url.com';
$driver = new \Behat\Mink\Driver\Selenium2Driver('firefox');
$this->minkSession = new \Behat\Mink\Session($driver);
$this->minkSession->start();
}
public function getCurrentPage()
{
return $this->minkSession->getPage();
}
public function getCurrentPageContent()
{
return $this->getCurrentPage()->getContent();
}
public function visit($url)
{
echo $url;
$this->minkSession->visit($url);
}
public function login($user, $pass){
$this->minkSession->visit('complete url');
$page = $this->getCurrentPage();
echo $page;
$page->fillField('email', $user); // Enter username.
$page->fillField('password', $pass); // Enter password.
$page->pressButton('Login');
$content = $this->getCurrentPageContent();
$this->assertContains('logout', $content);
}
/**
* #afterClass
*/
public function logout(){
$page = $this->getCurrentPage();
$page->clickLink('logout');
}
}
use PHPUnit\Framework\TestCase;
class MinkPetitionTest extends TestCase
{
use MinkSetup;
public function testSubmitPage(){
$this->login('user', 'pw'); // Login first.
$this->visit('full url');
$page = $this->getCurrentPage(); // Get the page.
echo $page;
$page->fillField('form_ban_id', '1234');
$page->pressButton('form_find_student');
$content = $this->getCurrentPageContent(); // Get page content.
$this->assertContains('<u>No Petitions</u> exist for Some User Student ID: 1234', $content);
}
}
$client = new MinkPetitionTest(); //tried to get something to work
$client->testSubmitPage(); //same here
You need to change your test class like so if you are using the latest phpunit:
...
use PHPUnit\Framework\TestCase;
class MinkPetitionTest extends TestCase
{
...
Can you try that first and see the result?
EDIT #2
Also, your trait file is incorrect. it should be:
trait MinkSetup
{
private $minkBaseUrl;
...
public function visit($url)
{
$this->minkSession->visit($this->minkBaseUrl . $url);
}
...
Try that

how to use global variables in php class in a MVC project

I want to $st_id in a function in my model class in a mvc project, as you see below, but it get me an error that $st_id is not defined. what I can do for resolve this problem ?
<?php
#session_start();
$st_id=$_SESSION['username'];
if (!isset($_SESSION['USERNAME']))
{
header('Location: signin.php');
}
//////////////////////
class model
{
private $result;
public $rp_result;
//////////
public function exe_query()
{
$mysqldb = new MySQLDatabase();
$result=$mysqldb->query('CALL view_report('.$this->st_id.');');
$this->rp_result=$mysqldb->fetch_all($result);
}
}
?>
How do you call your model ?
I suggest you:
class model
{
private $result;
public $rp_result, $st_id;
public function __construct($st_id)
{
$this->st_id = $st_id;
}
public function exe_query()
{
$mysqldb = new MySQLDatabase();
$result=$mysqldb->query('CALL view_report('.$this->st_id.');');
$this->rp_result=$mysqldb->fetch_all($result);
}
}
And now, you can use:
#session_start();
$st_id=$_SESSION['username'];
if (!isset($_SESSION['USERNAME']))
{
header('Location: signin.php');
}
$model = new model($st_id);
$model->exe_query();
You have to declare it within the class if you're using it with $this
class model {
public $st_id;
public function __construct() {
#session_start();
$this->st_id = $_SESSION['username'];
}
public function exe_query()
{
$mysqldb = new MySQLDatabase();
$result=$mysqldb->query('CALL view_report('.$this->st_id.');');
$this->rp_result=$mysqldb->fetch_all($result);
}
}
Why not call it directly as $_SESSION['username']? It's already global...

Categories