Error: Calling a class for no reason - php

The error is:
Class 'Controller\Index' not found
but in all my code at any time I call this class:
Test.php << Script Executor
include_once("index.engine.php");
Index::importController();
use Controller\User;
echo User::getWorld(); // The error happens here.
Index.engine.php << Indexer Includes
if (!defined('HOME')) define("HOME", __DIR__."/");
class Index{
public static function importModel(){
spl_autoload_register(function ($class) {
$nome = str_replace("\\", "/" , $class . '.model.php');
if( file_exists( HOME . $nome ) ){
include_once( HOME . $nome );
}
});
}
public static function importController(){
spl_autoload_register(function ($class) {
$nome = str_replace("\\", "/" , $class . '.controller.php');
if( file_exists( HOME . $nome ) ){
include_once( HOME . $nome );
}
});
}
public static function importPersistent(){
spl_autoload_register(function ($class) {
$nome = str_replace("\\", "/" , $class . '.persistent.php');
if( file_exists( HOME . $nome ) ){
include_once( HOME . $nome );
}
});
}
}
user.controller.php << Only an intermediary
namespace Controller{
include_once (__DIR__ ."/../index.engine.php");
Index::importPersistent();
use Persistent\Test;
class User{
public static function getWorld(){
$result = Test::getEngine();
return $result;
}
}
}
user.persistent.php << Function required
namespace Persistent{
class Test{
public static function getEngine(){
$engine = "Engine is on! \o/";
return $engine;
}
}
}
Thanks for help me.

use Controller\User; # this is used to call a namespace, in your code there is no declaration of the namespace
echo User::getWorld(); //
For this, one would be expected to have a file in this form
sample.php
namespace Controller;
class User {
public static function getWorld() {
...
}
}

user.controller.php
namespace Controller{
include_once (__DIR__ ."/../index.engine.php");
Index::importPersistent();
use Persistent\Test;
class User{
public static function getWorld(){
$result = Test::getEngine();
return $result;
}
}
}
I change to:
namespace Controller{
use Index;
use Persistent\Test;
Index::importPersistent();
class User{
public static function getWorld(){
$result = Test::getEngine();
return $result;
}
}
}
The error was in the include which was called more than once, then altered to call only once in the view.

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

How to create an object from a class inside another class

I have a problem creating an object from another class inside the constructor of my kernel class, it gives a fatal error which says can not find the class, anybody can help please? I do not know what is wrong?
namespace App\Http;
use App\Http\Config;
use App\Controllers;
class kernel{
protected $controller = "HomeController";
protected $action = "index";
protected $params=[];
public function __construct(){
$url = $this->ParseUrl();
$format_url = ucfirst($url[0]) . "Controller";
if (file_exists(Config::CONTROLLERS_PATH . $format_url . ".php")) {
$this->controller = $format_url;
}
// $path = Config::CONTROLLERS_PATH . $this->controller . ".php";
// echo "path: $path";// path is correct
require_once (Config::CONTROLLERS_PATH . $this->controller . ".php");
// $include_file = get_required_files();
// var_dump($include_file);//require_once is working
//here is the problem
$this->controller = new $this->controller;
}
public function ParseUrl(){
if (isset($_GET['url'])) {
return explode("/", rtrim($_GET['url'], "/"));
}
}
}

Function to send controller variable to view

For the setting up of a small home framework, I want to send variables to the view, but I have to date find no solutions that works.
The code in question:
src/Controller/Controller.php
<?php
namespace App\Controller;
use App\Network\Request;
class Controller {
protected $viewPath = ROOT . VIEW;
protected $template = ROOT . TEMPLATE;
protected $layout = "default";
public function __construct()
{
$request = new Request();
$this->render($request->controller().'/'. $request->action());
}
public function layout($template) {
if($template != $this->layout) {
require $this->template . $template . '.php';
}
}
public function render($view) {
ob_start();
require $this->viewPath . '/' . str_replace('.', '/', $view). '.php';
$content = ob_get_clean();
require $this->template .$this->layout . '.php';
}
public function set($varname) {
extract($varname);
return $varname;
}
}
?>
app/Controller/PostsController.php
<?php
namespace App\Controller;
class PostsController extends Controller {
public function index() {
$posts = [
"id" => "1",
"ids" => "2"
];
$this->set(compact('posts'));
}
}
?>
Using the $this->set function in PostsController returns me Undefined variable: posts after an echo.
I also try to put ob_start and ob_get_clean in the set function but do not work either.
Namely, I do not want to include the function set in render, since I handle the view of the view dynamically (see __construct ()).
Another question:
How do I associate a View class with my views and thus use $this->method ().
Thank you
Your variables are only limited to function set scope. So you cannot see it in render function
Why won't you send array of values into the render function like that
public function render($view, array $params = []){
extract($params, EXTR_OVERWRITE);
ob_start();
require $this->viewPath . '/' . str_replace('.', '/', $view). '.php';
$content = ob_get_clean();
require $this->template .$this->layout . '.php';
}
then you call it like this
$this->render('hello', [
'name' => 'Mikołaj',
'surname' => 'Woźniak'
]);

Using $this when not in object context

I am seeing some weird error on my client website. It's code someone else made for him for his application. The error message is saying that $this when not in object context but the Class has been extended where from App.
Please help out.
Error
Fatal error: Using $this when not in object context in contactController.php on line 6
contactController.php
class contactController extends App{
public function index(){
$this->view('content'); //error mmessage is pointing here
}
}
app.php
class App{
public $controller;
public $method;
public $params = [];
public function view( $file ){
include( site_path() . '/views/' . $file . '.php' );
}
public function model( $file ){
require_once( site_path() . '/models/' . $file . '.php' );
}
public function engine(){
global $core_current_ControllerMethod, $core_current_controller, $core_current_method;
//Get the current controller and method from a helper function
$get_wc_cm = get_wc_cm();
//Assign it to the global variable
$core_current_ControllerView = $get_wc_cm;
//Seperate the controller and method
$cm = explode('#', $get_wc_cm);
$controller = !empty($cm[0])? $cm[0]: null; // This is the controller
$method = !empty($cm[1])? $cm[1]: null; // This is the method
//Assign it to the global varaible
$core_current_controller = $controller;
$core_current_method = $method;
//Assign it to the class variable
$this->controller = $controller;
$this->method = $method;
$ControllerFile = site_path(). '/controllers/' . $this->controller . '.php';
if( file_exists($ControllerFile) ){
require_once($ControllerFile);
new $this->controller;
$callback = is_callable(array($this->controller, $this->method), false);
if( $callback ){
call_user_func_array([$this->controller, $this->method], [$this->params]);
}
}
}
}
$app = (new App)->engine();
Try to change :
class contactController extends App{
public function index(){
$this->view('content'); //error mmessage is pointing here
}
}
To :
class contactController extends App{
public function index(){
parent::view('content'); //error mmessage is pointing here
}
}

php namespace and autoload

I have some class
/library/QPF/Loader.php
namespace QPF;
class Loader
{
protected static $loader = null;
public function __construct()
{
spl_autoload_register('QPF\Loader::_autoload');
}
public static function init()
{
if (null === self::$loader) {
self::$loader = new Loader();
}
return self::$loader;
}
public function _autoload($class)
{
//if (class_exists($class)) return true;
$classFile = str_replace('\\', '/', $class) . '.php';
require_once $classFile;
if (!class_exists($class)) throw new Extension('Not found class');
}
}
/library/Version.php
namespace QPF;
class Version
{
public function getVersion()
{
return '0.1';
}
}
/public/index.php
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../library');
define('APPLICATION_PATH', dirname(__FILE__) . '/../application');
require_once 'QPF/Loader.php';
QPF\Loader::init();
echo 'start';
use QPF;
$v = new QPF\Version();
var_dump($v);
echo 'ss';
Version class loading, but var_dump show what it's empty class without function getVersion();
startobject(QPF\Version)#2 (0) { } ss
Methods do not show up in var_dump or print_r output, as they are not part of the state of the object. Try calling the method; it should work as expected.

Categories