Jump to content

Search the Community

Showing results for tags 'oop'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I'm really confused and hoping someone can point me in the right direction. I feel this is one of those really simple things that I'm going to want to slap myself in the head over when it's resolved. It simply involves displaying a comment count in a certain area of my project. I have this method to display comments here -> <?php public function display($post_id) { $rule = "AND comment_status='approved' ORDER BY date_added DESC"; $field = "post_id"; $query = $this->_db->get(self::$_table, array($field, "=", $post_id), $rule); $this->_data = $query->all(); $this->_count = count($this->_data); $cnt = 0; foreach($this->_data as $obj) { $data = array( "id" => $obj->id, "post_id" => $obj->post_id, "commenter" => $obj->username, "comment" => $obj->body, "date" => date("F d, Y H:i:s", strtotime($obj->date_added)), "profile_pic" => $this->_user->profilePic($obj->username), ); echo HTML::comments($data, $cnt); $cnt++; } echo $this->count(); // JUST HERE FOR TEST PURPOSES } public function count() { return $this->_count; } The line that's commented for FOR TEST PURPOSES displays the comment count as expected. The issue arises when I port it to the display page. <h5 class="title"><?php echo $comment->count(); ?> Comments</h5> I get no error, but I get no number for the comment count either. I don't understand why. I've obviously done the instantiation at the top, I didn't overlook that (represented by $comment). As the count stands right now it should say '2 Comments'. The $this->count() test line works, why am I getting no result where it matters?
  2. I'm experiencing something that I've no idea how to understand it. I have the following methods -> <?php public function action($action, $table, $where = [], $rule = "") { if(count($where) === 3) { $operators = array('=', '<', '>', '<=', '<='); $field = $where[0]; $operator = $where[1]; $value = $where[2]; if(in_array($operator, $operators)) { if($rule == "") { $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?"; } else { $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ? {$rule}"; } if(!$this->query($sql, array($value))->error()) { return $this; } } } return false; } // public function get($table, $where = [], $column = "*", $rule = "") { // return $this->action("SELECT {$column}", $table, $where, $rule); // } public function get($table, $where = [], $rule = "") { return $this->action("SELECT *", $table, $where, $rule); } They're called like this -> <?php public function recent() { $rule = "ORDER BY RAND()"; $field = "type"; $type = "recent"; $query = $this->_db->get(self::$_table, array($field, "=", $type), $rule); print_r($query); } The code like it is here works. Where the weirdness comes in is if I use the commented out DB->get() method. When I switch it and use the get() method that is commented out in the above code I get a fatal error because it's parsing the query string as this -> The absolute only difference is adding in that $column parameter or not and when it's there this effed up query string is the result. Can one of you fine phreaks break it down for me, I've been staring at my code for an hour and can't figure it out. Thanks
  3. Good evening, Phreaks. Quick question. I have this method here -> public function get($table, $where = [], $column = "*") { return $this->action("SELECT {$column}", $table, $where); } It works great as long as the call to it includes the $where array. I want both $where and $column to be optional here and $where to be an array when it's included. if I only use the $table parameter (which is the only one I want to be required). I keep getting a Could one of you fine folks please explain to me about this error and why I need the $where parameter when I want it to be optional. Thank you
  4. Could someone explain to me why this connection/query succeeds <?php DB::getInstance()->query("SELECT username FROM users WHERE username=?", array("TechnoDiver")); But when I do this it comes back as failed <?php $user = DB::getInstance()->query("SELECT username FROM users WHERE username=?", array("TechnoDiver")); if($user) { echo "success -> "; } else { echo "fail -> "; } like I said I ran tests for the DB->query in the query method and it comes back successfully. It's only when I try to assign it that it comes back failed. Why??
  5. Good morning Freaks, I hope you're all having a productive week. I've a question about an issue I'm having accessing static properties. I've been doing some reading on them but haven't yet deployed one successfully. I have a bunch of classes and I want to make the database query tables all static so they can be used cross-class, so to speak. Here's a sample attempt -> class Post { private $conn; private $user_obj; public static $table = "posts"; public function __construct($conn, $username) { $this->conn = $conn; $this->user_obj = new User($conn, $username); // $this->table = "posts"; } and accessing it here -> public function getBreakingNews() { $query = mysqli_query($this->conn, "SELECT * FROM self::$table WHERE type='breaking' ORDER BY RAND()"); This gets me an error that $table doesn't exist as does using Post::$table. When I assign $this->table = 'posts' (the commented out line in __construct) and access it by $this->table all works great. What am I doing wrong that it won't find that public static property? In the manual there's this example, which I feel like I've stayed true to -> class Foo { public static $my_static = 'foo'; public function staticValue() { return self::$my_static; } } ..... print Foo::$my_static . "\n"; The only difference I see is that they're printing the value and I'm trying to use it in a database query. Can anyone guide me through this mistake I'm apparently making and can't see? I've tried both self::$table and Post::$table, self::table and Post::table, every permutation I can think of but still the variable is saying it's unassigned. Share your knowledge please
  6. I'm looking for some insight on where/how to look something up. I have a Post class and it's really messy so I'm trying to clean it up. There's a method - createPost() - that takes in 8 parameters from a form, does what's needed to them to prepare them for database and creates 7 more properties, as well. For a total of 15 fields being sent to the database. I want to create a sendPost() method to handle this. In creating this method I realized that all these parameters look and feel burdensome and there's no real connection between the 2 methods other than sharing a class. I'd like to look into how to make sendPost take however many of parameters from whichever method it's called for without always having to pass the same amount. So for example if sendPost is being called with createPost than it has to handle 15 parameters, but, later, if I want to call sendPost on an editPost method, for example, it may only need to send 6 parameters back to the database meaning the other 9 would have to be redundantly passed again. I seem to recall from Python years ago there was a way to do this but I can't remember and I really don't know what to even search for to research it. Any direction or resources or advice that anyone could share would be really helpful and appreciated. Thanks
  7. Good Morning, Freaks, I hope you're all well. I've a question - I've been researching coding image resize functionality. While looking into the functions I'd need to do this I came across very similar code used in examples from 3 different sources so decided this was good code to learn from. So I tweeked it a bit and put it into a class method -> public function imageResize($target, $newcopy, $w, $h, $ext) { list($orig_w, $orig_h) = getimagesize($target); $scale_ratio = $orig_w/$orig_h; if(($w / $h) > $scale_ratio) { $w = $h * $scale_ratio; } else { $h = $w / $scale_ratio; } $img = ""; if($ext == "gif" || $ext == "GIF") { $img = imagecreatefromgif($target); } else if($ext == "png" || $ext == "PNG") { $img = imagecreatefrompng($target); } else if($ext == "jpg" || $ext == "JPG" || $ext == "jpeg" || $ext == "JPEG") { $img = imagecreatefromjpeg($target); } $create_tci = imagecreatetruecolor($w, $h); imagecopyresampled($create_tci, $img, 0, 0, 0, 0, $w, $h, $orig_w, $orig_h); imagejpeg($create_tci, $newcopy, 80); } and then connected it to a button -> <?php require("assets/initializations.php"); if(isset($_POST['upload_image'])) { $image_obj = new Image($conn, $user); $image_obj->imageUpload(); } else if(isset($_POST['resize_image'])) { mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT); $image_obj = new Image($conn, $user); $kaboom = explode(".", $image_name); //object params $image_ext = $kaboom[-1]; $target_image = "/opt/lampp/htdocs/site/admin/img/$image_name"; $resized_image = "/opt/lampp/htdocs/site/admin/img/resized_$image_name"; $max_w = 150; $max_h = 150; $image_obj->imageResize($target_image, $resized_image, $max_w, $max_h, $image_ext); //header("Location: add_photo.php"); } ?> Setup: A preview button chooses the image, a preview which is displayed underneath it (using js). There's also an upload button to bring it into the sites file system. This functionality works fine. I've just added the resize button beside the preview button and connected the object method to it. Intended Result: The resize button resizes the previewed image and the resized image is now previewed instead of the original image. Result: Nothing. The button stays in the active state, but nothing happens. I get no warning nor error messages and absolutely nothing in dev tools to work from. Not sure what my next step would be outside asking more experienced coders Any advise or guidance on getting this resolved would be met with appreciation. TIA
  8. I've been trying to write some code that takes user supplied information, sends it to a database (phpmyadmin) and also displays it elsewhere in the app. I'm to the point I'm trying to get it to the database right now. The issue is that it's not making it to the DB and is being lost somewhere. There's no warnings, no errors, nothing being returned anywhere to help resolve the problem, except in the browsers dev tools and that is different whether it's chrome or FF. It's also something that I have trouble seeing being responsible for the loss of data. In Chrome it comes back as -> Page layout may be unexpected due to Quirks Mode In FF as -> Layout was forced before the page was fully loaded. If stylesheets are not yet loaded this may cause a flash of unstyled content. But, like I said, I can't see how this is to blame for the data not making it to the DB and I see no difference in the layout or style anyways. At the top of add_post.php is the following: <?php require("assets/initializations.php"); if(isset($_POST['add_post']) && !empty($_FILES['post_image'])) { $filename = $_FILES['post_image']['name']; $file_tmp_name = $_FILES['post_image']['tmp_name']; $filesize = $_FILES['post_image']['size']; $file_ext = explode('.', $filename); $file_act_ext = strtolower(end($file_ext)); $allowed = array('jpeg', 'jpg', 'png', 'gif'); if(!in_array($file_act_ext, $allowed)) { echo "<script>alert('File Type Not Allowed');</script>"; //not sure how well this size check is working, have to experiment more //also need to research how to do an initial image check } elseif($filesize > 10000000) { echo "<script>alert('Image Is Too Large');</script>"; } else { $file_new_name = uniqid('', true) . "." . $file_act_ext; $dir = "/opt/lampp/htdocs/qcic/usernet/img/"; $target_file = $dir . basename($file_new_name); move_uploaded_file($file_tmp_name, $target_file); $post_obj->addNews( $_POST['title'], $_POST['content'], $_POST['category'], $_POST['status'], $_POST['post_type'], $_POST['tags'], $target_file ); echo "<script>alert('Your Post Has Been Added');</script>"; mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT); } } ?> <?php require('includes/header.php'); ?> Most of it is handling the image. The Post and User objects are instantiated in initializations.php at the top. The image uploads fine, everything works except the post object. The class for that is -> <?php class Post { private $conn; private $user_obj; public function __construct($conn, $user) { $this->conn = $conn; $this->user_obj = new User($conn, $user); } public function addNews($title, $content, $category, $status, $type, $tags, $image) { if(!empty($title) && !empty($content)) { $title = strtoupper($title); $title = mysqli_real_escape_string($this->conn, $title); $content = nl2br($content); $content = mysqli_real_escape_string($this->conn, $content); $added_by = $this->user_obj->getUsername(); $query = mysqli_query($this->conn, "SELECT top_cat_id FROM top_categories WHERE top_cat_title='$category'"); $row = mysqli_fetch_array($query); $cat_id = $row['top_cat_id']; $statement = $this->conn->prepare("INSERT INTO news VALUES ('', '$title', '$content', '$added_by', '$category', '$cat_id', '$image', '$tags', '$status', '$type', '?', '?', '?', '?');"); if($statement) { $statement->execute(); } else { echo "You messed up somewhere"; } } } } ?> I'm not the best or most experienced coder, for sure, but in the few months I've been learning PHP I've written a few DB queries now and this looks right to me. The first attempt didn't have prepared statements but that wasn't getting the data to the DB either. I've checked that the number of fields being sent match the number of fields in the DB, been tinkering with a few small things since yesterday on it, nothing works and as I said, no error or warning is coming back to work from, no message at all to work from. The only thing it triggers is those 2 console messages I mentioned above and the image does get to its new location. It's to the point now I'm just blank-mindedly staring at code. I'm not even getting back the else echo "You messed up somewhere" error from the final if statement, just the javascript alert that it was sent correctly, which it wasn't. I can really use some guidance on this one, thank you
  9. I've been scrolling through some 3rd party code trying to get ideas and a deeper understanding of PHP. I came across these 2 simple methods in a class entitled 'Category' -> public function deleteCategory($id) { $query = mysqli_query($this->conn, "DELETE FROM top_categories WHERE top_cat_id=$id"); if($query) { return true; } else { return false; } } public function updateCategory($id, $category) { $query = mysqli_query($this->conn, "UPDATE top_categories SET top_cat_title='$category' WHERE top_cat_id=$id"); if($query) { return true; } else { return false; } } They're simple enough and work perfectly in the context of their functionality, but I don't understand how. Their instantiation and calls are ordinary but I don't understand how they do what they do. To me (a very untrained eye) they look like they initialize a variable ($query) and then check if it's initialized or not without actually doing anything with it. They've both been instantiated in a file that is included at the top of each page and the method calls are seemingly normal -> if(isset($_POST['edit_cat'])) { $cat_obj->updateCategory($cat_id, $_POST['cat_title']); header("Location: category.php?message=category-updated"); } if(isset($_GET['cat_id'])) { $cat_obj->deleteCategory($_GET['cat_id']); header("Location: category.php?message=deleted-successfully"); } Can someone with the time and will please explain how these 2 methods do the things they do?
  10. Hello everyone. I'm just learning programming. I have a class: class DbBox extends BoxAbstract { public function save() { } public function load() { } } This class has two methods, Load and Save. How to format them correctly so that they can save data to a file?
  11. Hello, I hope it's ok to ask this question here. I have a registration script, but I'm not sure how to handle it efficiently and I have some questions about it. This is used in the page 'signup.php'. The class is called 'User'. I haven't noticed any errors or bugs. It would be very useful for me to be aware of my mistakes. public function regUser($uname,$upass,$upassverify) { $new_password = password_hash($upass, PASSWORD_DEFAULT); if(!password_verify($upassverify, $new_password)) { // passwords are not the same (I thought it would be better to do this after hashing, but maybe it doesn't matter or it's worse. I'm not sure about it) $info = 'pass_err'; } $stmt1 = $this->db->prepare("SELECT * FROM users WHERE username=:uname"); $stmt1->execute(array(':uname'=>$uname)); if($stmt1->rowCount() > 0) { // this username has already been used $info = 'user_err'; } if (!$info) { $stmt2 = $this->db->prepare("INSERT INTO users(username,password) VALUES(:uname, :upass)"); $stmt2->bindparam(":uname", $uname); $stmt2->bindparam(":upass", $new_password); $stmt2->execute(); // succesfully made an account $info = "success"; } header("Location:/signup.php?status=".$info); exit(); } Am I using the prepared statements as how I should be using them? Is this a safe way of handling my data or do you see vulnerabilities? I'm using PRG to prevent resubmission but I want to show a 'everything is fine' or 'oh no, something went wrong' to the one who is signinup. If I now go to signup.php?status=success, i see 'eveything is fine', without actually signing up, is there a better way to do this or can I somehow prevent everyone being able to see this? As you might have noticed in my last post, my English is not very good, sorry about that. Thanks, Fabian
  12. I am getting Fatal error: Uncaught Error: Call to a member function real_query() on null with this code: public final function Retrieve($TABLE, $CRIT){ $_query = "SELECT * FROM `{$TABLE}` WHERE "; foreach($CRIT as $_field => $info){ $_query .= " `{$_field}` = `{$info}` &&"; } if($this->LINK->real_query(rtrim($_query, ' &'))){ return $this->LINK->store_result(); } else{ return json_encode(array("Error"=>$this->LINK->errno(), "Description"=>$this->LINK->error())); } } (LINK is my mysql_connect() result.) I have tried everything i can think of, ->query, going to mysqli_query, breaking it sown and using a $result variable, but nothing seems to work...
  13. I was practicing OOP and made a simple class to log logins. Does anyone see any problems with this or improvements that can be made? Any issue with using NOW() in the query string instead of a placeholder? In another thread, @Jaques1 said: How would I implement that? I rtfm and don't understand it as of yet. <?php // ---------------------------------------------------------------------------- // Database Connection // ---------------------------------------------------------------------------- $dbhost = 'localhost'; $dbname = 'test'; $dbuser = 'root'; $dbpass = ''; $charset = 'utf8'; $dsn = "mysql:host=$dbhost;dbname=$dbname;charset=$charset"; $opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; $pdo = new PDO($dsn, $dbuser, $dbpass, $opt); //------------------------------------------------------------------------ // //------------------------------------------------------------------------ $valid_login = new LogLoginStatus($pdo); $valid_login->validLogin('goodusername'); $invalid_login = new LogLoginStatus($pdo); $invalid_login->invalidLogin('bad_username', 'bad_password'); //------------------------------------------------------------------------ // //------------------------------------------------------------------------ class LogLoginStatus { /** * Log Valid/Invalid logins * * @param string login_username * @param string login_password */ public function __construct($pdo) { $this->pdo = $pdo; } function validLogin($username) { $sql = "INSERT INTO user_login (login_status, login_ip, login_username,login_password, login_datetime) values(?, INET_ATON(?), ?, ?, NOW())"; $stmt = $this->pdo->prepare($sql); $stmt->execute(array( 1, $_SERVER['REMOTE_ADDR'], $username, '***' )); } function invalidLogin($username, $password) { $sql = "INSERT INTO user_login (login_status, login_ip, login_username,login_password, login_datetime) values(?, INET_ATON(?), ?, ?, NOW())"; $stmt = $this->pdo->prepare($sql); $stmt->execute(array( 0, $_SERVER['REMOTE_ADDR'], $username, $password )); } } ?> CREATE TABLE `user_login` ( `login_id` int(11) NOT NULL AUTO_INCREMENT, `login_status` tinyint(1) DEFAULT NULL, `login_ip` int(10) unsigned DEFAULT NULL, `login_username` varchar(255) DEFAULT NULL, `login_password` varchar(255) DEFAULT NULL, `login_datetime` datetime DEFAULT NULL, PRIMARY KEY (`login_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  14. Hi all, I have just put together a tentative proof of concept MVC framework proposal. After many weeks of slogging through an array of PHP MVC tutorials and courses (some of which I paid for) I have decided to strip back all the frills, bells and whistles to try and put together a core proof of concept that uses best practices. In this simplified example I am trying to test the viability of the framework itself... so there is no routing code or query string management and the controller and action are hard coded. Here is the repository: https://github.com/JethroHazelhurst/psr-4-mvc I like this framework because it: Has clear seperation of concerns Is not cluttered with static functions Is clearly namespaced - thanks to the PSR-4 autoloading Has a clear way of passing data to and from the model - e.g. $this->_view->foo = $this->_model->getBar(); Below is the directory structure: and here is a print_r of my Object structure: Questions I am interested in hearing any feedback on the idea... I can't see any glaring issues at them moment. Some questions in the back of my mind are: Are there any dangers in heavily depending on the parent::__construct() function to call parent classes? In the controller, is passing data from Model to View using $this->_view->foo = $this->_model->getBar(); good practice? Are there any dangers in using Namespaces? I am also interested in reading up on MVC framework best practices so if anyone can recommend some resources I would be very grateful. It seems like there are a million ways to write an MVC framework, I am confused as to which way is best practice. EDIT: Hmm, can't seem to get a list to display here...
  15. I want to see your opinion about OOP and Procedural. Which method has more easier to code in PHP? I'm using Procedural, but I notice PHP can read OOP as C++. Which is better for PHP? Thanks, Gary
  16. Howdy, I am writing a forum from scratch because I like to play with fire. Moving on, I can't think of the best way to store table and column names in either variables or constants. And where to store them? Maybe in a new config.php file? I thought about it and not one sane idea entered my head. I really don't like to write them each time in my DB wrapper methods since if i change the name of a table or a column, the whole thing will fall apart. Currently i have it set like this: <?php class Posts extends DB { public function list_topics_based_on_category() { return $this->select_from_table_condition('posts_id, posts_title, posts_date, author_id', 'posts', 'posts_categories_id = 1'); } public function display_contributor_name_by_id($user_id_array) { $contributor_name = $this->select_from_table_condition_user_input('username', 'users', 'id = ', $user_id_array); return $contributor_name[0]['username']; } public function count_comments($topic_id) { return count($this->select_from_table_condition_user_input('comments_id', 'comments', 'comments_topic_id = ', $topic_id)); } public function select_single_topic($topic_id) { return $this->select_from_table_condition_user_input('*', 'posts', 'posts_id = ', $topic_id)[0]; } } Please help! Thank you very much!
  17. This is my first oop php library and wanted to get advice on how I can improve what I wrote. This is what I needed to do: I'm also not sure on what it meant by "proportionally resize the shape up or down, given a floating-point scale factor" I think what I did might be right but I could be wrong. Also am I supposed to have a new class for each shape or is there a better solution? Any help is much appreciated. <?PHP echo "Circle (r=5) <br/>"; $circle = new circle(5); $circle->getArea(); $circle->getPerimiter(); $circle->scale(up, .5); echo "Scaled up .5<br/>"; $circle->getArea(); $circle->getPerimiter(); echo "<br/>Right Triangle (a=4, b=5) <br/>"; $rt = new RightTriangle(4, 5); $rt->getArea(); $rt->getPerimiter(); $rt->scale(down, .5); echo "Scaled down .5<br/>"; $rt->getArea(); $rt->getPerimiter(); echo "<br/>Equilateral Triangle <br/>"; $et = new EquilateralTriangle(6); $et->getArea(); $et->getPerimiter(); $et->scale(up, .; echo "Scaled Up .8<br/>"; $et->getArea(); $et->getPerimiter(); echo "<br/>Rectangle<br/>"; $r = new Rectangle(8, 7); $r->getArea(); $r->getPerimiter(); $r->scale(down, .; echo "Scaled Down .8<br/>"; $r->getArea(); $r->getPerimiter(); echo "<br/>Square<br/>"; $s = new Square(25); $s->getArea(); $s->getPerimiter(); $s->scale(up, 2.5); echo "Scaled Up 2.5<br/>"; $s->getArea(); $s->getPerimiter(); echo "<br/>Parallelogram<br/>"; $p = new Parallelogram(5.7, 6.; $p->getArea(); $p->getPerimiter(); $p->scale(up, 1); echo "Scaled Up 1<br/>"; $p->getArea(); $p->getPerimiter(); class Circle { public function __construct( $radius ) { $this->radius = $radius; } public function getArea() { echo number_format(pow($this->radius, 2) * M_PI, 2)."<br/>"; } public function getPerimiter() { echo number_format(2 * M_PI * $this->radius, 2)."<br/>"; } public function scale($direction, $scale) { if($direction == 'up') { $this->radius = $this->radius + ($this->radius * $scale); } else { $this->radius = $this->radius - ($this->radius * $scale); } } } class RightTriangle { public function __construct( $a, $b ) { $this->a = $a; $this->b = $b; } public function getArea() { echo number_format(($this->a*$this->b/2), 2)."<br/>"; } public function getPerimiter() { echo number_format($this->a + $this->b + sqrt(pow($this->a, 2) + pow($this->b, 2)), 2)."<br/>"; } public function scale($direction, $scale) { if($direction == 'up') { $this->a = $this->a + ($this->a * $scale); $this->b = $this->b + ($this->b * $scale); } else { $this->a = $this->a - ($this->a * $scale); $this->b = $this->b + ($this->b * $scale); } } } class EquilateralTriangle { public function __construct( $a ) { $this->a = $a; } public function getArea() { echo number_format((sqrt(3)/4)*pow($this->a,2),2)."<br/>"; } public function getPerimiter() { echo number_format(3 * $this->a, 2)."<br/>"; } public function scale($direction, $scale) { if($direction == 'up') { $this->a = $this->a + ($this->a * $scale); } else { $this->a = $this->a - ($this->a * $scale); } } } class Rectangle { public function __construct( $w, $l ) { $this->w = $w; $this->l = $l; } public function getArea() { echo number_format($this->w * $this->l,2)."<br/>"; } public function getPerimiter() { echo number_format(2 * ($this->w + $this->l), 2)."<br/>"; } public function scale($direction, $scale) { if($direction == 'up') { $this->w = $this->w + ($this->w * $scale); $this->l = $this->l + ($this->l * $scale); } else { $this->w = $this->w - ($this->w * $scale); $this->l = $this->l - ($this->l * $scale); } } } class Square { public function __construct( $a ) { $this->a = $a; } public function getArea() { echo number_format(pow($this->a,2),2)."<br/>"; } public function getPerimiter() { echo number_format(4 * $this->a, 2)."<br/>"; } public function scale($direction, $scale) { if($direction == 'up') { $this->a = $this->a + ($this->a * $scale); } else { $this->a = $this->a - ($this->a * $scale); } } } class Parallelogram { public function __construct( $a, $b ) { $this->a = $a; $this->b = $b; $this->h = $a/$b; } public function getArea() { echo number_format($this->b * $this->h,2)."<br/>"; } public function getPerimiter() { echo number_format(2 * ($this->a + $this->b), 2)."<br/>"; } public function scale($direction, $scale) { if($direction == 'up') { $this->a = $this->a + ($this->a * $scale); $this->b = $this->b + ($this->b * $scale); } else { $this->a = $this->a - ($this->a * $scale); $this->b = $this->b - ($this->b * $scale); } } } ?>
  18. Good evening I hope someone would be so kind as to help me. I am completely new too php oop and I just need help with one tiny problem. I have written some code and I understand most of the concepts concerning oop in php, it's just that I am struggling with interfaces and I don't really see why it should be used if I can just create methods, but anyway I was told it is a good practice to use interfaces because one of the main reasons of oop is to re-use code, So I have implemented an interface but I can call the method with and without the implementation of the interface so I was kind of wondering, what the purpose of interfaces are? or am I doing something wrong?
  19. Hi I’m looking for a standalone PHP OOP framework or code that follows best practices using - PDO prepared statements - Singleton Design Pattern Not looking for a massive library, something short and sweat straight to the point Any comments, feedback would be appreciated
  20. Please see attached my bank account class files. The key guidance I need is how to instantiate a class from another class. For example, you can see in Customer.class.php, I instantiate a new Account, but am not sure how i pass in the balance and account number to Customer in order that they can instantiate the Account? This is the same as Account instantiate a BankCard object. I am a little confused - any help appreciated. BankAccountApp.zip
  21. Hi All, I've been interested in writing a PHP pdo configuration file so that I can include connections in various files on my site. While I was looking up some possible solutions I stumbled across an interesting post on stack overflow http://stackoverflow.com/questions/11369360/how-to-properly-set-up-a-pdo-connection The first responder suggested the code below. However, I don't understand how to access the connection and make query calls. I'm confused by how it's possible to return a variable name as an object { return new $name( $this->connection ) }. Also, If someone could explain what the author means by { $something = $factory->create('Something');}. Wouldn't the "Something" need to be a class? And how would that class get the db connection? All the best, Karma $provider = function() { $instance = new PDO('mysql:......;charset=utf8', 'username', 'password'); $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); return $instance; }; class StructureFactory { protected $provider = null; protected $connection = null; public function __construct( callable $provider ) { $this->provider = $provider; } public function create( $name) { if ( $this->connection === null ) { $this->connection = call_user_func( $this->provider ); } return new $name( $this->connection ); } } $factory = new StructureFactory( $provider ); $something = $factory->create('Something'); $foobar = $factory->create('Foobar');
  22. Hi, I'm quite new to OOP PHP and i'm trying to make a dynamic insert function , i've followed an example on Stackoverflow to do so since its my first try at making something dynamic.http://stackoverflow.com/a/13333344/3559635 It works but im still quite confused about the two foreach loops , and if possible could someone explain that part to me please and or is there an easier more clean way to do this for a new guy like me? Im sending my POST values from the index.php <?php include("Database.php"); $db = new Database(); var_dump($db); $table = "users"; $whitelist = array('username', 'password'); $data = array_intersect_key($_POST, array_flip($whitelist)); if(isset($_POST['username']) AND ($_POST['password'])) { $db->postTesting($data, $table); } else { echo "Please fill in everything!"; } Database.php <?php class Database { private $connection; private $typedb = "mysql"; private $host = "127.0.0.1"; private $dbname = "oopphp"; private $username = "root"; private $password = ""; public function __construct() { try{ $this->connection = new PDO($this->typedb. ":host=".$this->host. ";dbname=".$this->dbname, $this->username, $this->password); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this->connection; } catch(PDOException $e) { throw new Exception("Connection failed: ".$e->getMessage()); } } public function postTesting($data, $table) { try{ //var_dump($table, $data); $columns = ""; $holders = ""; foreach ($data as $column => $value) { //var_dump($column); //var_dump($value); $columns .= ($columns == "") ? "" : ", "; $columns .= $column; $holders .= ($holders == "") ? "" : ", "; $holders .= ":$column"; //var_dump($columns); //var_dump($holders); } $sql = "INSERT INTO $table ($columns) VALUES ($holders)"; //return $sql; $stmt = $this->connection->prepare($sql); //var_dump($stmt); foreach ($data as $placeholder => $value) { $stmt->bindValue(":$placeholder", $value); //var_dump($stmt); //var_dump($placeholder); //var_dump($value); } //var_dump($sql); //var_dump($stmt); $stmt->execute(); } catch(PDOException $rError) { throw new Exception("Registering Failed: ".$rError->getMessage()); } } } Im seriously confused about this part. foreach ($data as $column => $value) { //var_dump($column); //var_dump($value); $columns .= ($columns == "") ? "" : ", "; $columns .= $column; $holders .= ($holders == "") ? "" : ", "; $holders .= ":$column"; //var_dump($columns); //var_dump($holders); } Thanks in advance for the help
  23. I am really struggling with the logic aspect of my application. I can't picture the structure and get it clear in my mind. As a result, I can't code anything because I'm second-guessing myself at every turn. My application is pretty simple in reality. It's an application that keeps a record of all the different 'contracts'/'agreements' that my colleagues have signed. Some will have signed three or four depending on what systems they are working on. The application will run a cron, daily, and send out an email to anyone who's contract/agreement is about to expire with an invite for them to renew it. I have already built an application that has a login system and authentication (using Laravel). It was my first Laravel effort and I did it using a tutorial from YouTube. I figured I could use the one login from that to act as the administrator for this whole application. Once the administrator is in, they will be presented with a panel to do various things. This is the part I am stuck on. What do you all think of my "logic"? Here are the basic routes (forgetting the auth stuff which is already done); /contracts - to see a list of all the contact templates out there. /contracts/{contract-id} - to view the specific contract template /contracts/create - GET and POST to be able to add new contract templates for other systems /people - view all my colleagues on one page /people/{person-id} - view a specific colleague and all the contracts they have signed /people/create - GET and POST for this too to be able to add new colleagues to the system /people/{person-id}/create-new-contract - so this would add a record in to a third table which joins info from the people table and the contracts table to make a list of unique contract agreements for each person and their expiry date. GET and POST for this as well I suppose. Even as I'm writing this, I don't know if this will be needed because I might have an emailing class that might do this job better? Hence the writing of this post! /agreements/renew/{renew-code} - This will create a new record in the table and amend the old one to show that the previous agreement has expired and that a new one for the next 365 days is in place.As you can probably tell.. I am struggling a bit. Is there any advice you can give me to help me mentally map out my application before I start coding? I just want to get it right..
  24. I have been trying to figure out a somewhat complex set of functions to handle some product price calculations and display. I was thinking that building classes may be the best solution, but I don't completely know what I am doing with that either. I was hoping someone may be able to help me figure out the best solution for all this. This site is being built within wordpress. The pages load as follows, 1. Site determines client level: If no user is logged in, it defaults to client_lvl = high, if user is logged in, client_lvl may be set to an alternate value. (high, med, low) This should be loaded just once per site visit. I created this function: function get_client_lvl () {$user_id = get_current_user_id(); global $client_lvl; If ($user_id == 0) {$client_lvl= 'high';} Else {$client_lvl=get_user_meta($user_id, wpcf-client-lvl, true); } }//End function I tried converting it to a class, but I'm not sure I am doing it correctly. class ClientLvl { public $client_lvl ='high'; private $user_id; private function __construct() { $this->user_id= get_current_user_id(); } public function get_client_lvl () //check the client level from user meta- { $this->client_lvl If ($user_id != 0) {return get_user_meta($user_id, wpcf-client-lvl, true); } The rest of the functions are based on the following arrangement. Collections have multiple products which have multiple variations. The Products have a series of multiplier values attached to them. One for each client level. It also has a multiplier type (m_type) The variants then have the item specific details such as cost of goods sold (cogs), Area, sku, and name. 2. This function is used to determine which multiplier value will be used in the calculation. Used on collection and product pages to determine which multiplier value to use for calculation based on client level f unction get_multiplier($client_lvl) { $p_high= get_post_meta(get_the_ID(),'p_high','single'); $p_med= get_post_meta(get_the_ID(),'p_med','single'); $p_low =get_post_meta(get_the_ID(),'p_low','single'); if ($client_lvl == 'med') {$prices=array('high'=>$p_high,'med'=> $p_med);} elseif ($client_lvl == 'low') {$prices=array('high'=>$p_high,'low'=> $p_low);} else {$prices=array('high'=>$p_high);} }//End function I am assuminng that if I made this a class, I should just define the p_high (med, low) values and then display them with another object creation in another function? 3.These values will be used in another function to limit the number of images that a user can select for their product. $img_min= get_post_meta(get_the_ID(),'img_min','single'); $img_max= get_post_meta(get_the_ID(),'img_max','single'); 4. These are the formulas that are used to calculate the displayed price. I am not sure how to handle the image and image+commission options as they use the number of selected images to determine the price. But if no images are selected, I want it to display "This is the price/ image. One idea I thought of was to include the echo statements inside the switch options, but Im not sure how to handle the array. If the client level is High the function will only loop through once and will not have a was now price. but if it is anything else, then it will loop through twice and will have the was now echo statement. If I didnt have the special case in the image based calculations, then the was now function would work just fine. But I'm not sure where to put the conditional echo's for those functions. function calculate_price($m_type) { global $cogs; $cogs= get_post_meta(get_the_ID(),'cogs','single'); $img_cost=10; $prices= get_multiplier(); Foreach($prices as $multiplier) { switch ($m_type) { case 'Area': $area= get_post_meta(get_the_ID(),'area','single'); $total[]= $multiplier * $area; break; case 'Image': if(isset($img_count)) {$total[]= $multiplier * $cogs * $img_count;} else {$total[]= $multiplier * $cogs ;} // Displayed as $price/ Image using $img_count break; case 'Commission': $total[]= $multiplier + $cogs; break; case 'Flat': $total[]= $multiplier; break; case 'Commission+Image': if(isset($img_count)) {$total[]= $multiplier + ($img_cost*$img_count);} else {$total[]= $multiplier; } //Display "Price: ".$multiplier. "+".$img_cost ." /image" break; case 'Price': $total[]= $multiplier * $cogs; break; }}} 5. Function that displays the price result from the previous function. Does not currently account for the image or image+commission statements. I need to create a similar function that finds the lowest calculated price of a particular product group to display on the archive page for products. function was_now($client_lvl,$m_type) { $total=calculate_price($m_type); $p1=number_format($total[0],2,'.',','); If ($client_lvl == "high") { echo "is \${$p1}"; } else { $p2=number_format($total[1],2,'.',','); echo "WAS: \${$p1}<br/>"; echo "NOW: \${$p2}"; }} 6.This is the subloop of the product page that displays the variants for that product. Not fully coded yet. (This code is currently displayed in the template file itself opposed to a function. function uc_list_product($ID,$m_type) { get_page_children($ID); echo "<table> "; while ( have_posts() ) { the_post(); ?> <tr><?php if($m_type=='Image'){ $display= 'Price '. was_now($client_lvl,$m_type); //if images are selected display price*img count } elseif($m_type=='Commission+Image'){ $display= 'Price '. was_now($client_lvl,$m_type);} //display multiplier, img cost, img count else {$display= 'Price '. was_now($client_lvl,$m_type);} echo "<td>". the_title()."</td><td>Price ".$display ."</td><td><a href='#'>Select Product</a></td></tr>" ; } echo "</table>"; wp_reset_query(); } This will probably be doable with classes, but I I'm not entirely sure how to go about that. I hope someone can help me figure this out.
  25. Hi. I haven't done a lot of OOP. Hardly any really. I've had a go at writing a very small class that outputs a greeting depending on what time of day it is. What do the OOP experts here make of it? What do you like, what do you hate? Is there anything I could do to make it more useful? Here is the code; class Greeting { // the __construct didn't do what I originally wanted. Denfine the hour outside the method (I don't know why this is a good/bad idea) /* public function __construct() { $hour_of_day = date('G'); } */ public function callGreetingPhrase() { return $this->getGreetingPhrase(); } // the setter doesn't seem to have a purpose here. I tried using it so that I could pass in a value of my choosing (for testing purposes) can't get it to work though /* public function setGreetingPhrase($value) { $this->hour_of_day = $value; } */ private function getGreetingPhrase() { $hour_of_day = date('G'); if($hour_of_day < 12 ) { // if it's before 12pm $greeting_phrase = "good morning"; } elseif($hour_of_day >= 12 && $hour_of_day < 18 ) { // if it's after 12pm but before 6pm $greeting_phrase = "good afternoon"; } else { // what is left over - after 6pm until midnight $greeting_phrase = "good evening"; } return $greeting_phrase; } } $greeting = new Greeting; echo $greeting->callGreetingPhrase(); It annoyed me that I could 't figure out how to use the __constructor here to store the hour. But should that have bothered me? Can someone maybe explain a bit about the setter that I tried to use setGreetingPhrase. I only put it in because I've seen other Classes with one. Could I use a setter method here for anything useful? Any feedback appreciated!
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.