Register for your free account! | Forgot your password?

Go Back   elitepvpers > Coders Den > Web Development
You last visited: Today at 00:35

  • Please register to post and access all features, it's quick, easy and FREE!

Advertisement



Namespaces und Static functions

Discussion on Namespaces und Static functions within the Web Development forum part of the Coders Den category.

Reply
 
Old   #1
 
elite*gold: 0
Join Date: Dec 2014
Posts: 276
Received Thanks: 84
Namespaces und Static functions

Heyho.
Ich versuche mich aktuell nochmal in Static functions und hauptsächlich auch Namespaces einzuarbeiten, jedoch gelingt mir das gerade nicht so wirklich.

PHP Code:
namespace Me\Classes;
use 
PDO;
use 
PDOStatement;
class 
Loader
{
    static 
$host '';
    static 
$database '';
    static 
$dbusername '';
    static 
$dbpassword '';
    static 
$pdo;

    static function 
__construct(){
        
self::$pdo = new PDO("mysql:host=localhost;dbname=dbname"self::$dbusernameself::$dbpassword);
        
self::$pdo->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
        return 
self::$pdo;
    }
     static function 
LoadUsers(){
        
$stmt self::$pdo->prepare("SELECT * FROM `users`");
        
$stmt->execute();
        
$users$stmt->fetchAll();
        return (
$users);
    }

Der Loader.

Wenn ich jetzt zb in die Index.php folgendes schreibe:

PHP Code:
Use Me\Classes\Loader;
$users Loader::LoadUsers(); 
Dann bekomme ich nen Statuscode 500 bei Twig (Weiße Seite).
Sobald ich in die Index zb namespace Me\Main oder Me\Index schreibe, dann gibt twig auch nen Status Code 500 aus.
Was genau mache ich falsch? x.x
.Barone is offline  
Old 01/13/2017, 17:48   #2

 
iKyroja :>'s Avatar
 
elite*gold: 20
Join Date: May 2010
Posts: 2,792
Received Thanks: 1,988
500 ist bei Twig glaube ich wenn etwas nicht definiert ist.
Dump doch einfach mal deinen Loader aus.
iKyroja :> is offline  
Old 01/13/2017, 17:55   #3


 
False's Avatar
 
elite*gold: 0
The Black Market: 243/0/0
Join Date: Apr 2011
Posts: 11,115
Received Thanks: 2,436
Quote:
Originally Posted by .Barone View Post
Heyho.
Ich versuche mich aktuell nochmal in Static functions und hauptsächlich auch Namespaces einzuarbeiten, jedoch gelingt mir das gerade nicht so wirklich.

PHP Code:
namespace Me\Classes;
use 
PDO;
use 
PDOStatement;
class 
Loader
{
    static 
$host '';
    static 
$database '';
    static 
$dbusername '';
    static 
$dbpassword '';
    static 
$pdo;

    static function 
__construct(){
        
self::$pdo = new PDO("mysql:host=localhost;dbname=dbname"self::$dbusernameself::$dbpassword);
        
self::$pdo->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
        return 
self::$pdo;
    }
     static function 
LoadUsers(){
        
$stmt self::$pdo->prepare("SELECT * FROM `users`");
        
$stmt->execute();
        
$users$stmt->fetchAll();
        return (
$users);
    }

Der Loader.

Wenn ich jetzt zb in die Index.php folgendes schreibe:

PHP Code:
Use Me\Classes\Loader;
$users Loader::LoadUsers(); 
Dann bekomme ich nen Statuscode 500 bei Twig (Weiße Seite).
Sobald ich in die Index zb namespace Me\Main oder Me\Index schreibe, dann gibt twig auch nen Status Code 500 aus.
Was genau mache ich falsch? x.x
Als Tipp, schau dir nicht nur an was du beim Browser zurück bekommst sondern schau in Logs.

Du machst folgendes :
Code:
 $stmt = self::$pdo->prepare("SELECT * FROM `users`");

Das kann aber nicht klappen da $pdo NULL ist.
Wieso $pdo NULL ist ?
Das liegt daran das der constructor nur aufgerufen wird wenn von der Klasse eine Instanz erzeugt wird was bei einem static Call nicht passiert.
False is offline  
Thanks
1 User
Old 01/13/2017, 18:00   #4
 
elite*gold: 0
Join Date: Dec 2014
Posts: 276
Received Thanks: 84
PHP Code:
use Me\Classes\Loader;
$usersLoader::LoadUsers
echo $twig->render('register.html', array('users'=>$users 
register.html
PHP Code:
{{ dump(users) }}

{{ 
dump }} 
Es wird nichts gedumpt. Also ist theoretisch $users leer?
.Barone is offline  
Old 01/13/2017, 18:03   #5

 
iKyroja :>'s Avatar
 
elite*gold: 20
Join Date: May 2010
Posts: 2,792
Received Thanks: 1,988
Muss nicht sein, was .ƒaℓsє. oben geschrieben hat wird wohl der fehler sein.
In deiner LoadUsers function ist die variable $pdo nicht definiert.
iKyroja :> is offline  
Old 01/13/2017, 18:18   #6
 
elite*gold: 0
Join Date: Dec 2014
Posts: 276
Received Thanks: 84
Okay, danke euch.

Jetzt frage ich mich wie man das ordentlich umsetzt ohne große workarounds..
.Barone is offline  
Old 01/13/2017, 18:32   #7


 
False's Avatar
 
elite*gold: 0
The Black Market: 243/0/0
Join Date: Apr 2011
Posts: 11,115
Received Thanks: 2,436
Quote:
Originally Posted by .Barone View Post
Okay, danke euch.

Jetzt frage ich mich wie man das ordentlich umsetzt ohne große workarounds..
Generell sollte (finde ich) solche Sachen Function nicht static sein.Statische Methoden kannst du nutzen für z.b "convertUkToGermanDate" oder "EurToDollar" oder "createUser(array $data)" etc....

Du solltest eine Haupt Klasse haben (deine Application), von dort aus hast du zugriff auf weitere Controller (Datenverarbeitung) diese Controller haben Zugriff zu einem Repository z.b. (in deinem fall) UserRepository, diese holen nur Daten.


Dann gibt es natürlich noch die Action, diese holt einfach nur die Sachen aus dem Html bzw bereitet diese für das Html vor.


Sprich der Workflow zum anzeigen von User wäre:


Action => Controller => Repository


P.s. In der Hauptklasse hast du dann z.b. auch die Datenverbindung die du in die Repositorys/Controller(je nach dem) weiter gibst.
Somit erzeugst du nicht in jeder Klasse (wo nötig) eine neue Verbindung.
False is offline  
Old 01/13/2017, 22:50   #8
 
Mikesch01's Avatar
 
elite*gold: 203
Join Date: Sep 2007
Posts: 732
Received Thanks: 190
Was zu dem Beispiel des TE gut passt ist das Singleton Pattern.

Mikesch01 is offline  
Old 01/14/2017, 12:36   #9
 
elite*gold: 0
Join Date: Dec 2014
Posts: 276
Received Thanks: 84
@mikesch01
Das hatte ich mir angeschaut, gefällt mir so aber nicht wirklich.

Wäre es so nicht umsetzbar?
Das ist jetzt zb die Registrierung vom User.
Wenn der User die Daten eingibt, werden diese an die Register.php weitergeleitet.

PHP Code:
 $register Handler\UserHandler::registerUser($_POST['username'],$_POST['password'],$_POST['email']); 
PHP Code:
namespace Me\Handler\HandlerUser;
use 
Me\Classes\user as User;
use 
Me\Loader\CoreLoader as Loader;
use 
Me\Wrapper\DatabaseWrapper as Wrapper;
use 
Exception;
use 
PDO;

Class 
UserHandler extends User\User
{
static function 
registerUser($name,$password,$email){
$pdo Wrapper::getPDO();

...
}

Wrapper:
PHP Code:
namespace Me\Wrapper;
class 
DatabaseWrapper
{
   private 
$pdo;

public static function 
getPDO()
        {
            
$host 'localhost';
            
$database '';
            
$username '';
            
$password '';
                
$pdo = new PDO("mysql:host=$host;dbname=$database"$username$password);
                return 
$pdo;
        }

Kriege hier auch nen 500 Statuscode.. mh.
.Barone is offline  
Old 01/14/2017, 13:12   #10
 
Mikesch01's Avatar
 
elite*gold: 203
Join Date: Sep 2007
Posts: 732
Received Thanks: 190
Code:
class DatabaseWrapper
{
   private $pdo;
   /* .. */
}
Statische Methode benötigen auch statisch Variablen. Statisch bedeutet ja, an die Klasse gebunden und nicht an eine Instanz (new ...).

Richtig wäre:
Code:
class DatabaseWrapper
{
   private static $pdo;
   
   public static function getPDO()
        {
            $host = 'localhost';
            $database = '';
            $username = '';
            $password = '';
                self::$pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password);
                return self::$pdo;
        }
}
Aber theoretisch erzeugst du immer noch bei jedem Aufruf ein neues PDO Objekt und das macht das statische auch nicht besser.

Noch besser wäre folgendes:
PHP Code:
namespace Me\Wrapper;
class 
DatabaseWrapper
{
   private static 
$pdo null;

   private 
initPDO() {
      
$host 'localhost';
      
$database '';
      
$username '';
      
$password '';
      
self::$pdo = new PDO("mysql:host=$host;dbname=$database"$username$password);
   }

   public static function 
getPDO()
        {
                if(
self::$pdo == null) {
                   
initPDO();
                }
                return 
self::$pdo;
        }

Programm:
PHP Code:
$db Me\Wrapper\DatabaseWrapper::getPDO(); 
Mikesch01 is offline  
Old 01/14/2017, 13:33   #11
 
elite*gold: 0
Join Date: Dec 2014
Posts: 276
Received Thanks: 84
Obwohl meine Augen funktionsfähig sind denke ich manchmal das ich blind bin.

Ich habe es so wie du geschrieben hast, umgestzt (1:1), jedoch sagt mir phpstorm:

"undefined function initPDO();"

Und Twig haut nen 500 Statuscode raus.

Edit:
Es wird daran liegen das
$db = Me\Wrapper\DatabaseWrapper::getPDO();
null ist.
.Barone is offline  
Old 01/14/2017, 14:09   #12


 
False's Avatar
 
elite*gold: 0
The Black Market: 243/0/0
Join Date: Apr 2011
Posts: 11,115
Received Thanks: 2,436
Quote:
Originally Posted by .Barone View Post
Obwohl meine Augen funktionsfähig sind denke ich manchmal das ich blind bin.

Ich habe es so wie du geschrieben hast, umgestzt (1:1), jedoch sagt mir phpstorm:

"undefined function initPDO();"

Und Twig haut nen 500 Statuscode raus.

Edit:
Es wird daran liegen das
$db = Me\Wrapper\DatabaseWrapper::getPDO();
null ist.
Und nochmal: Schau dir die Logs an!!!
Zudem wäre eine richtige IDE (z.b. PhpStorm) von vorteil, dann würdest du sehen das schon alles Rot markiert ist.Er hat dort :
PHP Code:
private initPDO() { 
stehen anstatt:
PHP Code:
private static function initPDO() { 
desweiteren ist auch das falsch :
PHP Code:
initPDO(); 
dort müsste folgendes stehen :
PHP Code:
self::initPDO(); 
Ich stelle mir immer noch die Frage wieso muss sowas Static sein ?
False is offline  
Old 01/14/2017, 15:15   #13
 
elite*gold: 0
Join Date: Dec 2014
Posts: 276
Received Thanks: 84
Quote:
Originally Posted by .ƒaℓsє. View Post
Ich stelle mir immer noch die Frage wieso muss sowas Static sein ?
Ich nutze PHPstorm, jedoch sind die angaben von PHPstorm nicht immer korrekt, da zb die Ordnerstruktur etwas anders ist aufm Server.

Es muss nicht umbedingt Static sein, aber irgendwie bring ich hier gerade glaube was durcheinander.

Ich habe in die Logs geschaut, da steht das PHP Fatal error: Class 'Me\\Handler\\HandlerUser' not found in register.php on line 22.

line 22:
PHP Code:
$register Me\Handler\HandlerUser::registerUser 
Handler:
PHP Code:
 static function registerUser($name,$password,$email)
    {
    } 
.Barone is offline  
Old 01/14/2017, 15:26   #14


 
False's Avatar
 
elite*gold: 0
The Black Market: 243/0/0
Join Date: Apr 2011
Posts: 11,115
Received Thanks: 2,436
Quote:
Originally Posted by .Barone View Post
Ich nutze PHPstorm, jedoch sind die angaben von PHPstorm nicht immer korrekt, da zb die Ordnerstruktur etwas anders ist aufm Server.

Es muss nicht umbedingt Static sein, aber irgendwie bring ich hier gerade glaube was durcheinander.

Ich habe in die Logs geschaut, da steht das PHP Fatal error: Class 'Me\\Handler\\HandlerUser' not found in register.php on line 22.

line 22:
PHP Code:
$register Me\Handler\HandlerUser::registerUser 
Handler:
PHP Code:
 static function registerUser($name,$password,$email)
    {
    } 
1.Wieso hat man auf dem Server eine andere Struktur ?
2.PhpStorm zeigt solche Fehler immer richtig an!
3.Dann haste ja dein Fehler gefunden, die Klasse ist nicht geladen(include/alternativ ein autoloader nutzen)
False is offline  
Reply


Similar Threads Similar Threads
MMONinja Static - Behemoth Static for End Game Raiding
08/25/2014 - Final Fantasy XIV - 3 Replies
Like the title says, I'm forming a static of "enhanced" players on Behemoth Server for players using "MMONinja" tools for FFXIV (or something comparable). The purpose will be to farm end game content including Coil & EX Primals. Now you don't "Have" to be using MMONinja, but you do have to be using some form of legitimate tools that can do similar things. Also, I'd want to verify you're actually using them so I know it's not just someone trolling us or trying to cause problems in game. ...
All Quest Functions Over 670 functions
06/08/2013 - Metin2 PServer Guides & Strategies - 21 Replies
Gretings this is very simple tut ther is all organized quest functions based on last pub rev 2089 If you know some quest functions is not ther let me know "if valid function of corse" addimage addmapsignal add_bgm_info
DMA to Static
05/27/2010 - Tutorials - 3 Replies
This is the best tut on defeating dma with code injection, that I found out there:



All times are GMT +1. The time now is 00:37.


Powered by vBulletin®
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
SEO by vBSEO ©2011, Crawlability, Inc.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Support | Contact Us | FAQ | Advertising | Privacy Policy | Terms of Service | Abuse
Copyright ©2026 elitepvpers All Rights Reserved.