Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 13
  1. #1

    Questa classe è progettata bene?

    Ciao belli, sto realizzando un applicazione, abbastanza complessa in realtà, ebbene si trattasi di un "social network" tempo permettendo, fino ad ora ho usato solo librerie di funzioni, ma per la gestione del profilo utente ho scelto di utilizzare questa classe
    Codice PHP:
    class account{
        
    /*
        @packages profilefunction.php
        Mario d'errico
        prorpietà nome cogome etc
        */
        
        
    public $nome;
        public 
    $cognome;
        public 
    $live;
        public 
    $interessi;
        public 
    $biobreve;
        public 
    $profile;
       
        
    /* cambia il nome   */ 
        
    public function changename($nome){
            if (empty (
    $nome)){
                return 
    true;
                
                }
                else{ 
                
    $profile $_SESSION['mail'];    
                
    $this->nome $nome;
                
    $query mysql_query ("
                update utenti 
                set nome = '
    $nome
                where mail = '
    $profile'
                "
    );  
             
               
               }
               
           }
           
          
    /* cambia il cognome*/
        
    public function changesurname($surname){
             if (empty(
    $surname)){
                 return 
    true;
                 }else{
                 
    $profile $_SESSION['mail'];
                 
    $this->cognome $surname;
                 
    $query mysql_query ("
                 update utenti 
                 set cognome = '
    $surname'
                 where mail = '
    $profile'
                 
                 "
    );
                
                 }
             }
         
    /*cambia dove vivi*/
         
    public function updatelive($location){
             if (empty (
    $location)){
                return 
    true
                }else{
                
    $profile $_SESSION['mail'];
                
    $this->live $location;
                
    $query mysql_query ("
                update utenti 
                set live = '
    $location'
                where mail = '
    $profile'
                "
    );    
                    
                }
             
             }
        
    /*cambia l'hobby */
        
    public  function updatehobby($hobby){
              if (empty (
    $hobby)){
                  return 
    true;
              }
              if (
    strlen ($hobby)> 20){
                  print 
    "Non superare i 20 caratteri nella sessione interessi";
                  
              }else{
               
    $profile $_SESSION['mail'];
                
    $this->interessi $hobby;
                
    $query mysql_query ("
                update utenti 
                set hobby = '
    $hobby
                where mail = '
    $profile'
                "
    );      
                  
              }
              
          }
          
    /*cambia bio breve*/
      
    public function updatesmallbio($smallbio){
             if (empty (
    $smallbio)){
                 return 
    true;        
              }
              if (
    strlen ($smallbio) > 260){
                echo 
    "Superato limite 260 caratteri";  
                  
              } else{
                
    $profile $_SESSION['mail'];
                
    $this->biobreve $smallbio;
                
    $query mysql_query ("
                update utenti 
                set bio = '
    $smallbio'
                where mail = '
    $profile'
                "
    );  
                  
              } 
             
          }
     
         
        }
        
    /*istanze e ogetti creati*/
     
    $newprofile = new account();
    $newprofile->changename($nome =htmlspecialchars (mysql_real_escape_string(stripslashes ($_GET['nome']))));
    $newprofile->changesurname($surname htmlspecialchars (mysql_real_escape_string(stripslashes($_GET['cognome']))));
     
    $newprofile->updatelive($location htmlspecialchars (mysql_real_escape_string (stripslashes ($_GET['live']))));
    $newprofile->updatehobby($hobby =htmlspecialchars (mysql_real_escape_string (stripslashes ($_GET['interessi']))));
    $newprofile->updatesmallbio($smallbio htmlspecialchars (mysql_real_escape_string (stripslashes ($_GET['bio'])))); 
    Credo che sia abbastanza semplice da capire in più e parzialmente commentata;
    la domanda è la seguente:"E' utile , è un modo di programmare corretto, avreste qualche altro metodo da incrementare, cambiereste qualcosa?."


    Ciauzz
    01001101 01000001 01010010 01001001 01001111 01000000 01001101 01001111 01001110 01000101☺☻

  2. #2
    Moderatore di PHP L'avatar di Alhazred
    Registrato dal
    Oct 2003
    Messaggi
    12,505
    Se vuoi uniformarti a quella che è una pratica diffusa per i nomi delle funzioni che modificano i valori degli attributi della classe, dovresti usare set_nome(), set_cognome() ecc...

    Tu oltretutto alcune le chiami update... altre change... il che crea confusione.

    Altre cose
    1) una classe dovrebbe come minimo avere i così detti metodi "getter" e metodi "setter", ovvero una funzione per ogni attributo che ne restituisca il valore, altrimenti come fai a recuperarlo?
    Esempio
    function get_nome() { return $nome; }

    ed una funzione set per ogni attributo modificabile.

    2) Nelle funzioni che attualmente usi per modificare gli attributi restituisci TRUE se in realtà non devi modificare l'attributo, ma non restituisci niente se invece lo devi modificare.
    O fai restituire qualcosa ad entrambi i casi o non fai restituire niente da nessuno.
    Ovviamente devi scegliere la prima opzione, ovvero far restituire qualcosa in entrambi i casi.
    Che succede se l'update sul DB fallisce e non ritorni FALSE? Tu pensi di aver effettuato la modifica e invece non è avvenuta.

    3) Manca il costruttore che inizializzi gli attributi.

    Queste sono le cose che mi sono venute in mente al volo, non escludo che ci sia altro da rivedere.

  3. #3
    cioè tu stai facendo 5 query per fare l'update di 5 campi di una tabella? Evviva le ottimizzazioni!!!

    questo tanto per iniziare:

    Codice PHP:
    <?php

    class Account{

        private 
    $nome
        private 
    $cognome
        private 
    $live
        private 
    $interessi
        private 
    $biobreve
        private 
    $profile

        public function 
    get_nome(){ return $this->nome; }
        public function 
    set_nome($nome){ $this->nome $nome; }

        
    //altri getter e setter

        
    public function save(){
        
    //creo la query di update per salvare tutti i campi in un colpo solo
        
    }

    }

    $account = new Account();
    $account->set_nome("pippo");
    $account->set_cognome("pluto");
    ...
    $account->save();
    poi manca il costruttore, un sistema per la validazione dei dati, un sistema per slegarla dal database, etc...
    IP-PBX management: http://www.easypbx.it

    Old account: 2126 messages
    Oldest account: 3559 messages

  4. #4
    Grazie ragzzi, per le cicche...solo questo non ho capito..
    un sistema per la validazione dei dati, un sistema per slegarla dal database, etc...
    [EDIT]
    Scusa santino, hai fatto un ottima osservazione, come faresti per ovviare il problema, nel codice che hai postato hai messo l'getto save , pensi che è possibile passare come argomento le query nell'ogetto stesso, non so se mi sono spiegato..
    01001101 01000001 01010010 01001001 01001111 01000000 01001101 01001111 01001110 01000101☺☻

  5. #5
    esempio su due campi

    Codice PHP:

    <?php

    class Account{

        private 
    $nome;
        private 
    $cognome;

        public function 
    __construct($nome=null,$cognome=null){
            
    $this->nome $nome;
            
    $this->cognome $cognome;
        }

        public function 
    set_nome($nome){ $this->nome $nome; }
        public function 
    get_nome(){ return $this->nome; }

        public function 
    set_cognome($cognome){ $this->cognome $cognome; }
        public function 
    get_cognome(){ return $this->cognome; }

    }

    class 
    AccountValidator{

        private 
    $errors = array();
        private 
    Account $account;

        public function 
    __construct(Account $account){
            
    $this->account $account;
        }

        public function 
    get_account(){ return $this->account; }

        public function 
    get_errors(){ return $this->errors; }

        public function 
    validate(){

            if(!
    $this->account->get_nome())
                
    $this->errors['nome'] = "Inserire un nome";

            if(!
    $this->account->get_cognome())
                
    $this->errors['cognome'] = "Inserire un cognome";

            return 
    $this->errors false true;
        }
    }

    class 
    AccountTable{

        public static function 
    save(Account $account){
            
    //creo la query per salvare l'account
            //salvo l'account nel database
            //ritorno TRUE/FALSE per segnalare il successo o meno dell'operazione
        
    }

    }


    $account = new Account("foo","bar");
    $validator = new AccountValidator($account);

    if(
    $validator->validate()){
        if(
    AccountTable::save($account))
            echo 
    "account salvato";
        else
            echo 
    "errore nel salvataggio";
    }else{
        echo 
    "errore nella validazione dei dati: ".print_r($validator->get_errors(),true);
    }

    lascia perdere l'uso di static in AccountTable, era giusto per fare un esempio
    IP-PBX management: http://www.easypbx.it

    Old account: 2126 messages
    Oldest account: 3559 messages

  6. #6
    Ok grazie santino, devo rivedermi l'opp, praticamente ho scritto del procedurale, in una classe...

    01001101 01000001 01010010 01001001 01001111 01000000 01001101 01001111 01001110 01000101☺☻

  7. #7
    perchè mi vengono in mente certe cose
    Codice PHP:

    interface updateuser{
        public function 
    set_name();
        public function 
    set_surname();
            public function 
    set_live();
        public function 
    set_bio();
            public function 
    set_hobby();
        public function 
    calldbandsave();
            public function 
    filtre();
        
        }

    class 
    createfunction implements updateuser{
        public 
    $name;
        public 
    $surname;
        public 
    $live;
        public 
    $bio;
        public 
    $hobby;
        public 
    $who__;
        public 
    $update;
        public 
    $error = array (
        
        
    "inserire un nome da 0 a 10 caratteri alfa numerici",
        
        
    "inserire un cognome da 0 a 10 caratteri alfa numerici",
        
        
    "non superare i 15 caratteri nella sessione '\vivi\'",
        
        
    "non superare i 160 caratteri nella sessione biobreve",
        
        
    "non superare i 15 caratteri nella sessione hobby",
        
        
    "image/jpd");
        function 
    __construct(){
            
    $this->name htmlspecialchars  ($_GET['nome']);
            
    $this->surname $_GET['cognome'];
            
    $this->live $_GET['live'];
            
    $this->bio $_GET['bio'];
            
    $this->hobby $_GET['interessi'];
            
    $this->who__ $_SESSION['mail'];
            
            }
      
       public function 
    set_name(){
              if ( empty (
    $this->name)){
                  return 
    true;
              } if (
    ctype_alnum ($this->name) && strlen ($this->name) > && strlen ($this->name) < 11){
                  
    $query mysql_query ("update utenti 
                  set nome = '
    $this->name
                  where mail = '
    $this->who__'");
                  return 
    true;
               }else{
                   echo 
    $this->error[0];
                   
                   }
               
           
         }
             
        public function 
    set_surname(){
             if ( empty (
    $this->surname)){
                  return 
    true;
              } if (
    ctype_alnum ($this->surname) && strlen ($this->surname) > && strlen ($this->surname) < 11){
                  
    $query mysql_query ("update utenti 
                  set cognome = '
    $this->surname
                  where mail = '
    $this->who__'");
                  return 
    true;
               }else{
                   echo 
    $this->error[1];
                   
                   }
            
            
            
            }    
        
        public function 
    set_live(){
            if (empty (
    $this->live)){
                return 
    true;
                
            } if (
    ctype_alnum ($this->live) &&  strlen  ($this->live) <= 15){
                 
    $query mysql_query ("update utenti 
                  set live = '
    $this->live
                  where mail = '
    $this->who__'");
                  return 
    true;
                
            }else{
                
    print_r ($this->error[2]);
                
                }
            
            
            
            }
            
            
        public function 
    set_bio(){
            
            if (empty (
    $this->bio)){
                return 
    true;
                
            } if (
    ctype_alnum ($this->bio) &&  strlen  ($this->bio) <= 160){
                 
    $query mysql_query ("update utenti 
                  set bio = '
    $this->bio
                  where mail = '
    $this->who__'");
                  return 
    true;
                
            }else{
                
    print_r ($this->error[3]);
                
                }
            
            
            
            
            }
        public function 
    set_hobby(){
            
            if (empty (
    $this->hobby)){
                return 
    true;
                
            } if (
    ctype_alnum ($this->hobby) &&  strlen  ($this->hobby) <= 15){
                 
    $query mysql_query ("update utenti 
                  set hobby = '
    $this->hobby
                  where mail = '
    $this->who__'");
                  return 
    true;
                
            }else{
                
    print_r ($this->error[4]);
                
                }
            
            
            
            
            }        

             } 
    Comunque le classi funzionano entrmbe, per ciò che concerne le "query multipli" il problema non sussiste, vengono richiamte per metodi e si "avviano" solo una alla volta..

    01001101 01000001 01010010 01001001 01001111 01000000 01001101 01001111 01001110 01000101☺☻

  8. #8
    ma che è quella robaccia?

    soprattutto: ma a cosa ti serve dichiare una interfaccia????

    mah, fai te... la prossima volta allora non chiedere consiglio visto che hai tenuto sempre lo stesso approccio di prima
    IP-PBX management: http://www.easypbx.it

    Old account: 2126 messages
    Oldest account: 3559 messages

  9. #9
    ciao santino non è che non voglio ascoltare, ma non capisco, ad esempio il __distruct() è una specie di garbagecollection...come se usassi unset, quanto come e perchè creare un interfacca allora, devo ancora entrare bene nell'ottica della opp, non è che non voglio ascoltare, ma quando programmo mi si ficca un ragionamento in testa e poi mi viene difficile capire qulli degl'altri....
    come gestiressi return


    Cmq ribadisco le calssi funzionano benissimo,,,,almeno quello
    01001101 01000001 01010010 01001001 01001111 01000000 01001101 01001111 01001110 01000101☺☻

  10. #10
    Originariamente inviato da MARIO@MONE
    Cmq ribadisco le calssi funzionano benissimo,,,,almeno quello
    mica ho detto "guarda che non funzionano", ti ho solo detto "ma che è quella robaccia" __distruct non è una "garbage collection", e dubito che in un linguaggio di scripting si possa parlare di garbage collection. __distruct è comodo per liberare risorse che l'oggetto possiede al momento in cui lo distruggi (via metodi tradizionali di php): ad esempio se ha un file handler, una resource ad un db, al distruct le puoi chiudere per essere sicuro di averle liberate, cose così insomma. Le interfacce definiscono un contratto a cui una o piu classi fanno fede. Ora, nel tuo caso, non credo che esisterà mai piu di una classe per fare l'update dell'account, visto che non penso che oggi usi un db e domani userai un file xml e dopodomani un file json (nel caso, l'interfaccia avrebbe senso in maniera che le tre classi per definire i tre tipi di storage, DB,XML e JSON di un account potrebbero essere poi usate trasparentemente dal programma grazie all'interfaccia comune). Quindi creare un'interfaccia in questo caso mi sembra abbastanza inutile e "buttato giù tanto per avere letto la parola interfaccia da qualche parte nel web". Per il resto, la testa è tua e i ragionamenti tuoi sicuramente vincono sui miei, però quella classe è confusa, i return sono a casaccio, invece di tornare l'errore fai una echo (alle volte anche una print_r)... cavolo, in caso di errore almeno ritorna false! al piu ti fai il metodo "last_errors()" e ritorni qual'era l'ultimo errore richiesto.



    poi te la butto li: se domani cambi database, passando da mysql a mongodb ad esempio, che fai? riscrivi tutta l'applicazione da capo? pensaci... e non pensare ad una soluzione visto che è cosa nota, al limite cerca su google

    EDIT: dimenticavo di ribadire un concetto: che una cosa "funzioni" non vuol dire che sia "fatta bene" (per evitare equivoci, per "fatta bene" intendiamo che segua i principi base dell'oop e i piu comuni design patterns universalmente accettati come ottimi modi di stesura del codice). Tu chiedevi nel thread "è fatta bene la classe?": la risposta è ovviamente no.
    IP-PBX management: http://www.easypbx.it

    Old account: 2126 messages
    Oldest account: 3559 messages

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.