Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class DatabaseObject {
- static protected $db;
- static protected $table_name;
- static protected $db_columns = [];
- public $errors = [];
- public static function set_db($db){
- self::$db = $db;
- }
- static public function find_by_sql($sql){
- $result = self::$db->query($sql);
- if(!$result) {
- exit("Database Query Failed");
- }
- //convert results into objects
- $object_array=[];
- while($record = $result->fetch_assoc()){
- $object_array[] = static::instantiate($record);
- }
- $result->free();
- return $object_array;
- }
- static public function find_all(){
- $sql = "SELECT * FROM " . static::$table_name;
- return static::find_by_sql($sql);
- }
- static public function find_by_id($id){
- $sql = "SELECT * FROM " . static::$table_name;
- $sql .= " WHERE id='" . self::$db->escape_string($id) . "'";
- $object_array = static::find_by_sql($sql);
- if(!$object_array){
- return false;
- }
- return array_shift($object_array);
- }
- static protected function instantiate($record){
- $object = new static;
- //could assign things by hand but its faster and easier to do it dunamically
- //plus it's reusable.
- foreach($record as $property => $value){
- if(property_exists($object, $property)){
- $object->$property = $value;
- }
- }
- return $object;
- }
- protected function validate() {
- $this->errors = [];
- $this->errors[] = "bar";
- return $this->errors;
- }
- protected function create(){
- $this->validate();
- if(!empty($errors))
- {return false;}
- $attributes = $this->sanitize_attributes();
- $sql = "INSERT INTO " . static::$table_name . " (";
- $sql .= join(',', array_keys($attributes));
- $sql .= ") VALUES ('";
- $sql .= join("', '", array_values($attributes));
- $sql .= "')";
- $result = self::$db->query($sql);
- if ($result){
- $this->id = static::$db->insert_id;
- }
- return $result;
- }
- //attributes are the properties which have the db columns excluding id
- protected function update(){
- $this->validate();
- if(!empty($errors)){return false;}
- $attributes = $this->sanitize_attributes();
- $attribute_pairs = [];
- foreach($attributes as $key => $value) {
- $attribute_pairs[] = "{$key}='{$value}'";
- }
- $sql = "UPDATE " . self::$db->escape_string(static::$table_name) . " SET ";
- $sql .= join(', ', $attribute_pairs);
- $sql .= " WHERE id='" . self::$db->escape_string($this->id) . "' ";
- $sql .= "LIMIT 1";
- $result = self::$db->query($sql);
- return $result;
- }
- public function save(){
- if(isset($this->id)){
- return $this->update();
- } else {
- return $this->create();
- }
- }
- public function merge_attributes($args){
- foreach($args as $key => $value) {
- if(property_exists($this, $key) && !is_null($value)){
- $this->$key = $value;
- }
- }
- }
- public function attributes() {
- $attributes = [];
- foreach(static::$db_columns as $column) {
- if($column == 'id'){ continue; }
- $attributes[$column] = $this->$column;
- }
- return $attributes;
- }
- protected function sanitize_attributes() {
- $attributes = $this->attributes();
- $sanitized =[];
- foreach($attributes as $key => $value){
- $sanitized[$key] = self::$db->escape_string($value);
- }
- return $sanitized;
- }
- public function delete(){
- $sql = "DELETE FROM " . self::$db->escape_string(static::$table_name) . " ";
- $sql .= "WHERE id='";
- $sql .= self::$db->escape_string($this->id);
- $sql .= "' LIMIT 1";
- $result = self::$db->query($sql);
- return $result;
- //after deleting the instance is still around
- //which is useful so you can say $this->poop was deleted
- //but we cant call CRUD functions
- }
- }
- class Admin extends DatabaseObject {
- static protected $table_name = 'admins';
- static protected $db_columns = ['id', 'first_name', 'last_name', 'email', 'username', 'hashed_password'];
- public $id;
- public $first_name;
- public $last_name;
- public $email;
- public $username;
- public $password;
- public $confirm_password;
- protected $hashed_password;
- protected $password_required = true;
- public function __construct($args = []){
- $this->first_name = $args['first_name'] ?? '';
- $this->last_name = $args['last_name'] ?? '';
- $this->email = $args['email'] ?? '';
- $this->username = $args['username'] ?? '';
- $this->password = $args['password'] ?? '';
- $this->confirm_password = $args['confirm_password'] ?? '';
- }
- public function label() {
- return $this->username . " Name: " . $this->first_name . " " . $this->last_name;
- }
- private function hash_password(){
- $this->hashed_password = password_hash($this->password, PASSWORD_BCRYPT);
- }
- protected function validate() {
- $this->errors = parent::validate();
- $this->errors[] = "foo";
- if(is_blank($this->first_name)) {
- $this->errors[] = "First name cannot be blank.";
- } elseif (!has_length($this->first_name, array('min' => 2, 'max' => 255))) {
- $this->errors[] = "First name must be between 2 and 255 characters.";
- }
- if(is_blank($this->last_name)) {
- $this->errors[] = "Last name cannot be blank.";
- } elseif (!has_length($this->last_name, array('min' => 2, 'max' => 255))) {
- $this->errors[] = "Last name must be between 2 and 255 characters.";
- }
- if(is_blank($this->email)) {
- $this->errors[] = "Email cannot be blank.";
- } elseif (!has_length($this->email, array('max' => 255))) {
- $this->errors[] = "Last name must be less than 255 characters.";
- } elseif (!has_valid_email_format($this->email)) {
- $this->errors[] = "Email must be a valid format.";
- }
- if(is_blank($this->username)) {
- $this->errors[] = "Username cannot be blank.";
- } elseif (!has_length($this->username, array('min' => 8, 'max' => 255))) {
- $this->errors[] = "Username must be between 8 and 255 characters.";
- }
- if(is_blank($this->password)) {
- $this->errors[] = "Password cannot be blank.";
- } elseif (!has_length($this->password, array('min' => 12))) {
- $this->errors[] = "Password must contain 12 or more characters";
- } elseif (!preg_match('/[A-Z]/', $this->password)) {
- $this->errors[] = "Password must contain at least 1 uppercase letter";
- } elseif (!preg_match('/[a-z]/', $this->password)) {
- $this->errors[] = "Password must contain at least 1 lowercase letter";
- } elseif (!preg_match('/[0-9]/', $this->password)) {
- $this->errors[] = "Password must contain at least 1 number";
- } elseif (!preg_match('/[^A-Za-z0-9\s]/', $this->password)) {
- $this->errors[] = "Password must contain at least 1 symbol";
- }
- if(is_blank($this->confirm_password)) {
- $this->errors[] = "Confirm password cannot be blank.";
- } elseif ($this->password !== $this->confirm_password) {
- $this->errors[] = "Password and confirm password must match.";
- }
- return $this->errors;
- }
- protected function create() {
- $this->hash_password();
- $result = parent::create();
- return $result;
- }
- protected function update(){
- if($this->password != ''){
- $this->hash_password();
- } else {
- $this->password_required = false;
- }
- $result = parent::update();
- return $result;
- }
- }
- //Bicycle is my post class. This is kind of embarrassing but I'm refreshing myself on OOP to get back into coding and I'm building a //fake bike store site.
- class Bicycle extends DatabaseObject {
- protected static $table_name = "bicycles";
- static protected $db_columns = ['id', 'brand', 'model', 'year', 'category', 'color', 'gender', 'price', 'condition_id', 'description', 'weight_kg'];
- public const CATEGORIES = ['road', 'mountain', 'hybrid', 'cruiser', 'city', 'BMX'];
- public const GENDER = ['mens', 'womens', 'unisex'];
- public $id;
- public $brand;
- public $model;
- public $year = 1987;
- public $category = self::CATEGORIES[0];
- public $color;
- public $gender;
- public $price = 0.0;
- public $condition_id;
- public $description;
- protected $weight_kg = 0.0;
- public const CONDITION = [
- 1 => 'Beat up',
- 2 => 'Decent',
- 3 => 'Good',
- 4 => 'Great',
- 5 => 'Like New'
- ];
- public function __construct($args=[]){
- $this->brand = $args['brand'] ?? null;
- $this->model = $args['model'] ?? null;
- $this->year = $args['year'] ?? $this->year;
- $this->category = $args['category'] ?? $this->category;
- $this->color = $args['color'] ?? null;
- $this->gender = $args['gender'] ?? null;
- $this->price = $args['price'] ?? $this->price;
- $this->condition_id = $args['condition_id'] ?? null;
- $this->weight_kg = $args['weight_kg'] ?? 0.0;
- //foreach($args as $k => $v) {
- //if(property_exists($this, $k)){
- //$this->$k = $v;
- //}
- //}
- }
- public function get_weight_kg(){
- return $this->weight_kg . " kg";
- }
- public function get_weight_kg_no_kg(){
- return $this->weight_kg;
- }
- public function set_weight_kg($value){
- $this->weight_kg = floatval($value);
- }
- public function get_weight_lbs(){
- return $this->weight_kg * 2.2046226218 . " lbs";
- }
- public function set_weight_lbs($value){
- $this->weight_kg = $value / 2.2046226218;
- }
- public function condition(){
- if($this->condition_id > 0 ){
- return Self::CONDITION[$this->condition_id];
- } else {
- return "unknown";
- }
- }
- public function name() {
- return $this->year . ' ' . $this->brand . ' ' . $this->model;
- }
- protected function validate(){
- $this->errors = parent::validate();
- if(is_blank($this->brand)){
- $this->errors[] = "Brand cannot be blank.";
- }
- return $this->errors;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement