Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: OOP - System Rezerwcacji
Forum PHP.pl > Forum > PHP
JakubBab
Czesc,

Pisze (dla praktyki) system wypozyczania ksiazek. Narazie skonczylem system rejestracji uzytkownikow. Jest to pierwszy projekt w OOP jaki robie wiec napewno sa bledy. Prosba o sprwadzenie formy i wskazowki jak i co polepszyc . Tak towyglada w plikach:

projekt/config/config.php
projekt/config/database.php

projekt/class/user.class.php
projekt/class/userException.class.php

projekt/controller/register.control.php

projekt/register.php

A tu kod:

config/config.php
  1. <?php
  2.  
  3. $host = substr($_SERVER['HTTP_HOST'],0,5);
  4.  
  5. if(in_array($host, array('local','127.0','192.1'))){
  6. $local=TRUE;
  7. }else
  8. {
  9. $local= FALSE;
  10. }
  11.  
  12. //determine location of files and the URL of the site:
  13. //allow for development on different servers.
  14.  
  15. if($local){
  16. $debug=TRUE;
  17. //define the constants:
  18. define('BASE_URI','c:\xampp\htdocs\library');
  19. define('BASE_URL','http://localhost/library/');
  20. define('DB','c:\xampp\htdocs\library\\config\database.php');
  21.  
  22. } // if there was a live server then the condition would have included live server defines
  23.  
  24. if(!isset($debug)){
  25. $debug=FALSE;
  26. }
  27.  
  28. // Custom defined error handler - no need to define it as of yet.
  29.  
  30. ?>


class/user.class.php

  1. /*
  2.  * user.class.php
  3.  * Adds user : First Name, Second Name, Email, ID - auto increment
  4.  * Checks if email is already in the db. - Unique email field
  5.  * Adds user into the detabase
  6.  */
  7.  
  8. class user{
  9.  
  10.  
  11. //db
  12. private $conn;
  13.  
  14. public $name,$surname,$email;
  15. public $password;
  16. public $_message; // for assigning errors
  17.  
  18. function __construct($db){
  19. $this->conn=$db;
  20. }
  21.  
  22. /*
  23. *Name: not numeric, less then 10 characters
  24. */
  25.  
  26. function checkName($name){
  27. $this->name=$name;
  28. if(!is_numeric($this->name)
  29. && strlen($this->name) < 10){
  30. return $this->name;
  31. }
  32. Throw New userException($this->_message,0);
  33. }
  34. /*
  35. * Surname: not numeric, less then 10 characters
  36. */
  37.  
  38. function checkSurname($surname){
  39. $this->Surname=$surname;
  40. if(!is_numeric($this->Surname)
  41. && strlen($this->Surname) < 10){
  42. return $this->urname;
  43. }
  44. Throw New userException($this->_message,1);
  45. }
  46.  
  47. /*
  48. * The password's first character must be a letter, it must contain at least 4
  49. * characters and no more than 15 characters and no characters other than letters,
  50. * numbers and the underscore may be used
  51. */
  52.  
  53. function checkPassword($password){
  54. $this->password=$password;
  55. if(strlen($this->password) < 10
  56. && preg_match('/^[a-zA-Z]\w{3,14}$/',$this->password)){
  57. return $this->password;
  58. }else{
  59. Throw New userException($this->_message,2);
  60. }
  61. }
  62.  
  63.  
  64. /*
  65.  * Password hashing
  66.  */
  67.  
  68. function setPassword($password){
  69. $this->password=sha1($password);
  70. return $password;
  71. }
  72.  
  73.  
  74.  
  75. function create(){
  76. $query= "insert into users SET name=?, Surname=?, email=?, password=?";
  77.  
  78.  
  79. $stmt = $this->conn->prepare($query);
  80.  
  81. $stmt->bindParam(1,$this->name);
  82. $stmt->bindParam(2,$this->Surname);
  83. $stmt->bindParam(3,$this->email);
  84. $stmt->bindParam(4,$this->password);
  85.  
  86. if($stmt->execute()){
  87. return TRUE;
  88. }else{
  89. Throw New Exception('email');
  90. }
  91.  
  92. }// end of create()
  93.  
  94.  
  95. } // end of main if
  96.  
  97.  


class/exception.class.php

  1. class userException extends Exception{
  2.  
  3. public function getDetails(){
  4.  
  5. switch ($this->code){
  6.  
  7. case 0:
  8. return '</br>Name. ';
  9. break;
  10. case 1:
  11. return '</br>Surname</br>Details given do not meet required criteria';
  12. break;
  13. case 2:
  14. return 'Password must contain 1 character, special sign, upper and lower case letters';
  15. break;
  16. case 3:
  17. return 'There is something wrong with the email';
  18. default:
  19. return 'no Further information is available';
  20. break;
  21.  
  22.  
  23. }
  24. }
  25.  
  26. }
  27.  


controller/register.control.php

  1. if(isset($_POST['send'])){
  2. if($_SERVER['REQUEST_METHOD']=='POST'
  3. && isset($_POST)
  4. && !empty($_POST)
  5. && filter_var($_POST['em'],FILTER_VALIDATE_EMAIL)
  6. ){
  7.  
  8. include_once('./class/user.class.php');
  9. include_once('./config/database.php');
  10. require_once('./class/exception.class.php');
  11.  
  12. $database = new Database;
  13. $db=$database->getConnection();
  14. $user= new user($db);
  15.  
  16.  
  17. try{
  18. $user ->name =$_POST['fn'];
  19. $user->checkName($user->name);
  20.  
  21. $user ->Surname = $_POST['sn'];
  22. $user->checkSurname($user->Surname);
  23.  
  24. $user ->password= $_POST['ps'];
  25. $user->checkPassword($user->password);
  26. $user ->setPassword($user->password);
  27.  
  28.  
  29. $user ->email = $_POST['em'];
  30.  
  31.  
  32.  
  33. if($user->create()){
  34.  
  35. Header('Location:./includes/good.php');
  36. }
  37. }catch(userException $e){
  38. echo "<div class=\"alert alert-info\" alert-dismissable\" id=\"err_blank\">";
  39. echo "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button>";
  40. echo "Please check the following: {$e->getDetails()}";
  41. echo "</div>";
  42. }
  43.  
  44.  
  45. } // end of secondary if
  46.  
  47. } // end of main if


view/register.php

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <!-- Required meta tags always come first -->
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  7. <meta http-equiv="x-ua-compatible" content="ie=edge">
  8.  
  9. <!-- Bootstrap CSS -->
  10. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
  11. <link rel="stylesheet" href= "css/bootstrap-theme.min.css">
  12. </head>
  13. <body>
  14. <h1>Registration Form</h1>
  15.  
  16. <!-- jQuery first, then Bootstrap JS. -->
  17. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  18. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
  19. </body>
  20. </html>
  21.  
  22. <!-- header -->
  23.  
  24. <?php
  25.  
  26. require_once('controller/register.control.php');
  27. ?>
  28.  
  29. <div id="wrapper">
  30. <div class="col-xs-3">
  31.  
  32. <form class="form-block" action="" method="post">
  33.  
  34. <div class="form-group">
  35. <label for="exampleInputName2">Name</label>
  36. <input type="text" class="form-control" name="fn" id="exampleInputName2" placeholder="First Name">
  37. </div>
  38. <div class="form-group">
  39. <label for="exampleInputName2">Surname</label>
  40. <input type="text" class="form-control" name="sn" id="exampleInputName2" placeholder="Surname">
  41. </div>
  42. <div class="form-group">
  43. <label for="exampleInputName2">Password</label>
  44. <input type="text" class="form-control" name="ps" id="exampleInputName2" placeholder="Password">
  45. </div>
  46. <div class="form-group">
  47. <label for="exampleInputEmail2">Email</label>
  48. <input type="email" class="form-control" name="em" id="exampleInputEmail2" placeholder="email adress">
  49. </div>
  50. <button type="submit" name="send" class="btn btn-primary">Register</button>
  51. </form>
  52. </div>
  53. </div>
viking
Niepotrzebnie nazywasz pliki ...class.php. Tak się robiło kilka lat temu. Poczytaj o PSR-4 + autoloader np. composera.
Stosuj modyfikator widoczności dla metod.
Klasa User to raczej jakiś service w tym wypadku. Jeśli rozdzielisz to do encji będziesz mógł łatwo wymieniać dane z tablicy POST do obiektu.
Stosuj rzutownie typów np. public function __construct(\PDO $db)
Walidacja jest w kilku miejscach.
Dlaczego hasło ma takie restrykcje? Wrzucaj je do password_hash/validate.
Zdecyduj się na jednolite nazewnictwo bo jest raz name a później Surname.
com
Wszystkie throw, new, header małymi literami, tak samo jak true, false.
Zadbaj o odpowiednie formatowanie, nwm jakiego edytora używasz ale przeważnie jest tak że zaznaczasz wszystko i alt + i (ctrl+alt+i).
Nie zapominaj o hermetyzacji, pola nie powinny być publiczne.

Jak popracujesz nad formatowaniem to nie będziesz potrzebował komentarzy końca metod itp wink.gif
JakubBab
Ok. Dzieki.

Poczytalem i dochodze do wniosku, ze... jeszcze raz to napisze.

Klasa - db - Singleton
Klasa action dla db - z delete, select itp.
I walidacja w jednym miejscu

Az takich restrykcji nie ma na haslo, bylo wieksze ale zmienilem na cos przyzwoitego. W switchu jest opis starego regex-u.

Pozmienialem widocznosc:

  1. private $conn;
  2.  
  3. private $name;
  4. private $surname, $email;
  5. private $password;
  6. private $_message;


Co do edytora - Aptana - moze komus sie przyda w przyszlosci - (ctrl+shift+F).

Niestety, reszte musze poprawic dopiero jutro. Bede update-owac.
com
pomyśl nad depedency injection, zamiast antywzorca Singleton wink.gif

undescore w nazwie raczej zbędne smile.gif
JakubBab
Cytat(com @ 1.02.2016, 17:09:25 ) *
pomyśl nad depedency injection, zamiast antywzorca Singleton wink.gif

undescore w nazwie raczej zbędne smile.gif



Czytam o DI i patrze na moj kod - czy przypadkiem nie ma tam dependency injection?

class db - odziellnie

class user
  1. class user {
  2.  
  3. //db
  4. // for assigning errors
  5.  
  6. function __construct(PDO $db) {
  7. $this -> conn = $db;
  8. }


no i register.class

  1. $database = new Database;
  2. $db = $database -> getConnection();
  3. $user = new user($db);


Widze, ze zle jest to rozlozone plikowo. Pisze od nowa. Sek jest w tym, czy jest to DI jesli nie, jak to ugryzc?
com
Ja nie powiedziałem że nie masz, powiedziałem żeby Singleton zastąpić DI smile.gif
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.