PHP - How Do You Handle System Objects Used In Almost Every Other Class?
Well in my script exist certain objects being used everywhere, in main script files and class library files. A good example is this Page class:
Code: [Select] <?php class Page{ public $type; public $name; private $title = ""; private $content = ""; private $date = ""; private $links; private $sidebar; private $ads; public function __construct($page = ""){ // Constructor method of page class } public function gettitle(){ if(empty($this->title)) throw new Exception('The page has no title.'); return $this->title; } public function settitle($title){ $title = secure($title); if(empty($title)) throw new Exception('Cannot set title for this page.'); else $this->title = $title; } public function getcontent(){ if(empty($this->title)) throw new Exception('The page has no content.'); return $this->content; } public function addcontent($content, $overwrite = FALSE){ $content = secure($content); if(empty($this->content) or $overwrite == TRUE) $this->content = $content; else $this->content .= $content; } public function getlinks(){ // the method that grabs user links } public function getsidebar(){ // the method that loads sidebar } public function getads(){ // the method that shows ads } public function display(){ // the method that format pages and brings everything together } } ?> Now lets say I have other classes such as User, Message and Item, a page object will need to be used inside some of their methods so that the page title/content can be modified when necessary. This seems to be quite problematic to me, since I have to declare this Page object global in every method that uses it. Similar problem occurs with my database object, and its even more annoying since almost half of my class methods need to use database queries and commands. So I was wondering... Is there a better way for me to handle these system objects such as Page and Database rather than having to declare them as global inside every single method that deals with them? Please help... Similar TutorialsHi All
I have not really played around with PHP in ages so I am having a hard time trying to figure out the best way to proceed. Anyhow... what I need to get done is to take a singleton pattern core database class that has a extended driver based class (ie; the type of database server the connection is connecting to), and build a new class that dynamically handles as many driver based connections that are called using a single instance. As a side note, I tried PDO but it only supports a single driver per class instance, and then each of those connections cannot not have their on set of properties that relate to each connection. Anyway, I was thinking that the best way to handle all the driver specific connections, is to hand out a 'unique hash reference' that points to an array of connection objects and the object properties. then when the client runs any sql function they pass the 'unique hash reference' which the class then returns the object and it properties that will be used by the class to call up the driver specific sql function that was requested by the client. So what do you all thing about that....
TIA stephanieT
PS...
I reason i need this is because I need to update up 25 different databases based on data stored on all the databases and not all of the database servers are of the same type, (ie; MSSQL, Oracle, MySQL, MariaDB, berkeley DB, postgres, sqlite2,3, etc, etc)! Edited January 16, 2019 by StephanieTI think this is what it is called... I having a brain fart... And I don't play with classes that much... Plus I have been playing with trying to get pdf's to output correctly so my brain is toasty.... I'm trying to parse DICOM (medical file format) files and I have this class and I want to setup an array to pull what fields I want. Code: [Select] <?php require '../dicomparser/nanodicom.php'; $filename = 'B4IBG5A0'; // 5) Load simple and print certain value try { //echo "5) Load simple and print certain value\n"; $dicom = Nanodicom::factory($filename); $dicom->parse(); //echo $dicom->profiler_diff('parse').'<br>'; echo 'Patient Name: '.$dicom->value(0x0010, 0x0010).'<br>'; echo 'Operators Name: '.$dicom->value(0x0010, 0x0040).'<br>'; echo 'Patient ID: '.$dicom->value(0x0010,0x0020).'<br>'; unset($dicom); } catch (Nanodicom_Exception $e) { echo 'File failed. '.$e->getMessage()."\n"; } //} ?> So what I want to do is have the array contain 'Patient Name' => '(0x0010, 0x0010)' etc... And have it something like this so I don't have to echo all the lines I want. Code: [Select] foreach ($array as $key => $value) { echo $key': '.$dicom->value.$value.'<br>'; } I can't get it to work... I remember figuring it out once before but that was over a year ago... And I don't have the code I wrote. I know it's something simple stupid. like $$ or [] i'm not getting the combination right. Thanks in advance... I can post some code once I am back at my laptop but for now thinking about this is keeping me awake in bed and all I have handy is my phone. Anyway, I am new to OOPHP. I have a class that I created. I have two objects/instances of it, each using some of the same and some different methods within the class. When I run the page either of the instances works great alone but I get the white screen of death when I try to use both instances at the same time. Any ideas or places I should start? I am a bit rusty with mySQL and I tried to borrow some other query code and modify it into an update command...apparently I am trying to use an invalid property in my error checking. Basically I just want to check and see if there were NO rows updated so I can let the user no that nothing was changed. There are probably easier ways to do this? The page where I set the variable values is based on a form post. I am not sure how to write my validation tests. Right now it is running the update successfully but it is reporting back an error based on hitting the "else if" test where I am trying to see if no rows were updated. The error message is: Quote Encountered error: 8 in /home/omgma/public_html/member_community/mbr_profiles/mbr_profile_updt_post.php, line 85: Trying to get property of non-object No fields were updated! Error: 0 Code: [Select] //create a SQL statement $updt_cmd = "UPDATE users t1, directory t2 " ."SET t1.email = '$email', " ."t2.first_name='$first_name', " ."t2.last_name='$last_name', " ."t2.suffix='$suffix', " ."t2.website_url='$website_url' " ."WHERE t1.username ='$username' AND t2.directory_id = t1.directory_id"; $conn = db_connect(); $result = $conn->query($updt_cmd); if (!$result) {//could not execute query throw new Exception('<h2>Could not execute member profile update!</h2><p>Error: ' .mysqli_errno($conn) .mysqli_error($conn) .'</p>' ); } else if ($result->num_rows==0) {// no rows so nothing was updated. throw new Exception('<h2>No fields were updated! </h2><p>Error: ' .mysqli_errno($conn) .mysqli_error($conn) .'</p>' ); } else { $mbr_profile = $result->fetch_object(); print_r($mbr_profile); return $mbr_profile; } Am I using the right functions here to do this and if so where can I find the class properties to use to test if nothing was updated? Thanks Hello everyone... I made point system that ranks users in my app. There are two parts to the system, a primary score and a dynamic score. The primary score is based on how you well you perform and the dynamic score is based on how well your friends perform. Both of these get added together to equal your total score. The problem is that I have a lot of looping occurring which results in about 400 queries being run when I access the page that executes this class. Can this be optimized? What's the best way to do this? I don't want to store the data as I want this presented in real-time. Code: [Select] <?php class edge { public function get_all_users_edge() { $sql = "SELECT id FROM users WHERE status = 3"; $result = mysql_query($sql) or die(mysql_error()); $ids = array(); while (($row = mysql_fetch_assoc($result)) !== false) { $ids[] = $row; } $all_edges = array(); foreach ($ids as $k => $id) { $edge = $this->get_users_edge($id['id']); $all_edges[$k] = $edge; } return $all_edges; } public function get_users_edge($uid) { $users_primary_edge = $this->get_users_primary_edge($uid); $users_dynamic_edge = $this->get_users_dynamic_edge($uid); return $users_primary_edge + $users_dynamic_edge; } public function get_users_primary_edge($uid) { if (active_id($uid) === false) { return false; } $uid = (int)$uid; $sql = "SELECT CHAR_LENGTH(`users`.`credentials`) AS `cred_chars`, CHAR_LENGTH(`users`.`specialties`) AS `spec_chars`, `companies`.`companyvideo` AS `video`, `investor_info`.`accredited` AS `accredited`, ( SELECT COUNT(`user_id`) FROM `blog_posts` WHERE `user_id` = '${uid}' ) AS `post_count`, ( SELECT COUNT(`uid`) FROM `votes` WHERE `uid` = '${uid}' ) AS `vote_sent_count`, `votes_received`.`inv_vote_received_count`, `votes_received`.`pub_vote_received_count`, ( SELECT COUNT(`userid`) FROM `employees` WHERE `userid` = '${uid}' ) AS `joined_count`, `votes2`.`ent_count`, `votes2`.`inv_count`, ( SELECT COUNT(`company_id`) FROM `company_fans` LEFT JOIN `companies` ON `company_fans`.`company_id` = `companies`.`companyid` LEFT JOIN `employees` ON `employees`.`companyid` = `companies`.`companyid` WHERE `userid` = '${uid}' ) AS `company_fans_count`, ( SELECT COUNT(`user_id`) FROM `recommendations` WHERE `user_id` = '${uid}' ) AS `recommendation_count`, ( SELECT COUNT(`partner_id`) FROM `partners` WHERE (`user_id` = '${uid}' OR `friend_id` = '${uid}') AND `approved` = '1' ) AS `associate_count` FROM `users` LEFT JOIN `investor_info` ON `investor_info`.`uid` = `users`.`id` LEFT JOIN `employees` ON `employees`.`userid` = `users`.`id` LEFT JOIN `companies` ON `employees`.`companyid` = `companies`.`companyid` LEFT JOIN ( SELECT `employees`.`userid`, SUM( IF( `votes`.`vote_type` = 1, 1, 0 ) ) AS `inv_vote_received_count`, SUM( IF( `votes`.`vote_type` = 0, 1, 0 ) ) AS `pub_vote_received_count` FROM `votes` INNER JOIN `employees` ON `employees`.`companyid` = `votes`.`company_id` WHERE `employees`.`userid` = '${uid}' GROUP BY `employees`.`userid` ) AS `votes_received` ON `votes_received`.`userid` = `users`.`id` LEFT JOIN ( SELECT `beta_keys`.`ref_id`, SUM( IF( `users`.`accounttype` = 1, 1, 0 ) ) AS `ent_count`, SUM( IF( `users`.`accounttype` = 0, 1, 0 ) ) AS `inv_count` FROM `beta_keys` INNER JOIN `users` ON `users`.`id` = `beta_keys`.`userid` WHERE `beta_keys`.`ref_id` = '${uid}' AND `users`.`status` = 3 GROUP BY `users`.`id` ) AS `votes2` ON `votes2`.`ref_id` = `users`.`id` WHERE `users`.`id` = '${uid}'"; $result = mysql_query($sql) or die(mysql_error()); $row = mysql_fetch_assoc($result); $score = 0; if((!empty($row['cred_chars'])) && (!empty($row['spec_chars']))) { $score += 200; } if(!empty($row['video'])) { $score += 50; } if($row['accredited'] == 1) { $score += 100; } $score += (50 * $row['post_count']); $score += (5 * $row['vote_sent_count']); $score += (3 * $row['inv_vote_received_count']); $score += (1 * $row['pub_vote_received_count']); $score += (200 * $row['joined_count']); $score += (40 * $row['ent_count']); $score += (200 * $row['inv_count']); $score += (10 * $row['company_fans_count']); $score += (30 * $row['recommendation_count']); $score += (20 * $row['associate_count']); return $score; } public function get_users_dynamic_edge($uid) { $uid = (int)$uid; $sql = "( SELECT `users`.`id` FROM partners INNER JOIN `users` ON `partners`.`user_id` = `users`.`id` WHERE partners.friend_id = '${uid}' AND `approved` = 1 ) UNION ALL ( SELECT `users`.`id` FROM `partners` INNER JOIN `users` ON `partners`.`friend_id` = `users`.`id` WHERE `partners`.`user_id` = '${uid}' AND `approved` = 1 )"; $result = mysql_query($sql) or die(mysql_error()); $i = 0; $score = 0; while (($row = mysql_fetch_assoc($result)) !== false) { $dynamic_scores[$i] = array( 'uid' => $row['id'], 'score' => $this->get_users_primary_edge($row['id']), ); $i++; } if(!empty($dynamic_scores)) { foreach($dynamic_scores as $k => $dynamic_score) { $score += $dynamic_score['score']; } } return ($score * 0.1); } } ?> Hello all!
I have this array of objects:
Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-20 07:39:55 [status] => 2 [approval_date] => 2014-09-20 07:40:41 [assessment_id] => 3 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-20 07:41:07 [mainmanger] => 3 ) [2] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )Where "id" = the user ID. If there are two or more entries for a user, I want to remove all but the most recent by the "approval_date",... So for the above example it would return: Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => piznac@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )I'm having a hard time wrapping my head around this concept, so I don't have any example code. And I don't really need or expect someone to code this for me,. just a push in the right direction would be awesome. I have the following three tables (and also delta_point and hist_point which are purposely left out and just mentioned for context). Before going down the Doctrine ORM long curvy road, aggrType was just used to restrict possible values so that I didn't need to use MySQL's ENUM, but now I am thinking there may be value to making it an entity and include some methods (and a second reason because I still can't figure out how to make Doctrine create a FK constraint yet not populate the parent entity with a AggrType object). point -id (int PK) -data -dType /* descriminator. Options are AggregatePoint, DeltaPoint, and HistoricPoint */ aggr_point -id (int PK, FK to point) -aggrType (char FK to aggrType) -data aggrType -type (char PK) /* there are about five types */ I have a service to create a new point based on the provided desired type and user data. I don't like the switch statement to determine which type of point to create, but don't know a better way. Also my entity is responsible to provide the appropriate validation rules for the given point type which might not be considered proper but it seems to work for me. Any constructive criticism is welcomed. <?php namespace NotionCommotion\PointMapper\Api\Point; use NotionCommotion\PointMapper\Domain\Entity\Point; class PointService { public function create(string $type, array $params):integer { $class=[ 'aggr'=>'AggregatePoint', 'delta'=>'DeltaPoint', 'hist'=>'HistoricPoint', ][$type]; //$class='Point\\'.$class; //This doesn't seem to be possible and I needed to use the fully qualifed name without the short cut used namespace. $class='\\Greenbean\Datalogger\Domain\Entity\Point\\'.$class; $point=new $class(); $validator=$this->getValidator($point); $params=$validator->sanitize($params); $validator->validate($params); $point->setAccount($this->account); $point->populate($params, $this->em); //Will be addressed later $this->em->persist($point); $this->em->flush(); $point->setIdPublic($this->em->getRepository(Point\Point::class)->getPublicId($point->getId())); return $point->getIdPublic(); } } Now, this is the part I am struggling with the most. I only have one service to create any type of point, so I do wish to put a bunch of if/thens in it and instead move logic to the individual point type being created. The AggrPoint in question requires a sub-point and I don't think it is appropriate to inject the entity manager into a point entity and as an alternative solution find an existing point which is associated with the account which resides in the new AggrPoint. Maybe not appropriate, but it works. This type of point also has a sub-object AggrType as discussed at the very beginning of this post, so I first attempt to create a new one from scratch, but that doesn't work and I need to set $aggrType with an existing one. As an alternative, I passed the entity the entity manager, but as stated I think this is a bad idea. Any recommendations where to go from here? Thank you namespace NotionCommotion\PointMapper\Domain\Entity\Point; class AggregatePoint extends Point { public function populate(array $params, \Doctrine\ORM\EntityManager $em):\NotionCommotion\PointMapper\Domain\Entity\Entity{ $criteria = \Doctrine\Common\Collections\Criteria::create() ->where(\Doctrine\Common\Collections\Criteria::expr()->eq("id_public", $params['pointId'])); if(!$subpoint = $this->getAccount()->getPoints()->matching($criteria)->current()){ throw new \Exception("Invalid subpoint ID $params[pointId]"); } $this->setSubpoint($subpoint); //This won't work since I must use an existing AggregateType and not create a new one $aggrType=new AggregateType(); $aggrType->setType($params['aggrType']); //This just seems wrong and I shouldn't be passing the entity manager to an entity $aggrType=$em->getRepository(AggregateType::class)->findOneBy(['type'=>$params['aggrType']]); $this->setAggregateType($aggrType); unset($params['pointId'], $params['aggrType']); // parent::populate($params) not shown, but it basically calles appropriate setters based on the property name return parent::populate($params); } public function getValidatorRules():array { return $this->filesToArr(['/point/base.json', '/point/aggr.json']); } }
hello dear PHP-Fans - greetings to you - and a happy new year!! i set up a WAMP-System on my openSuse 11.4 system. In order to learn as much as i can bout PHP i want to do some tests and write some scripts. Well the WAMP is allready up and running. Now i try to give the writing access to the folder mkdir /srv/www/ where the php-scripts should go in... i want to give write permission to all to all files in /srv/www As root I generally: mkdir /srv/www/ chown <webmaster usrername> /srv/www/ /srv/www/ should be readable and traversable by all, but only writeable by it's owner (the user designated as the webmaster.) can i do this like mentioned above,... Love to hear from you greetings db1 So I'm sitting at my desk scratching my head on how to do a task where I pull information form a database (that i know how to do) but then i need to see if two variables equal a string and if they do count out how many times that two variables equal there two string checks and out put the counted number ? this is what I have thought of but dose not to work because I cant figure out a way to code it? $dbPull = mysql_fetch_array($result) if( $dbPull['Foo'] == 'string1' && $bdPull['Bar'] == 'string2') this is were I get lost I'm looking for (how many times in the DB dose String2 show up in the array were the above, IF statement is true ) any ideas would be most appreciated So i got a table that looks somthing like this: File Name | Download | Suggested Catagory | Select Catagory | Approve -------------------------------------------------------------------------------------- test | Download | blah blah blah | Option menu | yes or no option menu test | Download | blah blah blah | Option menu | yes or no option menu test | Download | blah blah blah | Option menu | yes or no option menu what I want to do is in the file that processes this it only looks at the ones that have had the "approve column" submitted as a yes. Next it will to a mysql entry into verrified notes. Problem is with X amount of entries in that form I dont know how to look at only the ones that have said yes. Do I create a new form for each entry or put them all as one entry and after this what do I do next? Okay, so now I need help evolving my Log-In system... Up until now, the only place a user could log-in was on a given Article page if they wanted to add a comment to the Article. To accommodate that feature, I was setting the "Return To Page" only in my "article.php" script like this... Code: [Select] $_SESSION['returnToPage'] = $_SERVER['SCRIPT_NAME'] . '?title=' . $articleTitle; However, now I want to expand things. I'm growing increasingly confused about how to manage where to route people when they long-in?! 1.) Sometimes a user will Log-In and want to return where they were at (e.g. index.php, article1234.php) 2.) Sometimes a user might want to continue down a path (e.g. Checking Out, Registering for a Workshop, Sending a Message) Is there some kind of strategy to handle this? (nothing over complex, but there must be some Best Practices that work?! Debbie Hi all. I'm new to PHP language and I'd like to know which is the best way to handle the user login. With cookies or with sessions? Do you know some example on the web that I could inspire on? I just know how to do it in both way, I just wanna know which is the best way and like to read some code written by a pro. I have just completed a modest way for Users to post Comments on Articles my website. However, the thought occurred to me today, that I haven't given Users the ability to Preview or Edit their comments after submittal. What is the best way to store info on a Comments Form so you can re-display it for Preview/Editing?? (I'm not really sure how the workflow would work for this?!) Do I capture the Comments Form Data and store it in a Session? Or in my Database? Or do something else? Security is always a concern of mine too!! Thanks, Debbie Is there a "PREFERRED METHOD" to handling telephone numbers gathered by a form? I'm torn between ideas. I need to collect the numbers, and want to be able to view them as (123)555-1212. Should I collect them as a 10 digit ONLY string, and strip them into area code, parenthesis, and hyphenated LATER? Or gather them as 3 seperated input boxes posted to the DB accordingly? Obviously, entries will have REQUIREMENTS and error messages, so I am focused on the methodology here. Thanks. Hi guys On the edit profile page on my website, im trying to get is so that when the user first opens the page, if the database field reads "1" the checkbox is checked. However if the user unchecks it and makes a mistake on the form which returns an error, the checkbox remains unchecked. Also if the user unchecks the text box, the 1 in the database is changed to a 0. And vise versa. The only way i have got it to work succesfully is by using the following: <?php $test = $_POST['test']; $submit = $_POST['submit']; if (!isset($test)) { $test="0"; } else { $test="1"; } if ($submit) { mysql_query("UPDATE profiles SET test='$test' WHERE username='user'"); echo "ok"; } ?> <html> <form action="test.php" method="POST"> <input type="checkbox" name="test" <?php if ($submit) { if ($test=="1") { echo "checked='checked'";}} else { if ($row['test'] == "1") {echo "checked='checked'";}} ?> /> <input type="submit" name="submit" /> </form> </html> My problem is, i have about 60 check boxes on the page, and i dont really want to write the code below for all of them: if (!isset($test)) { $test="0"; } else { $test="1"; } Does anybody know a better way to do this so i dont end up with 420 lines of extra code? Many thanks. May you help me with how to get a file handle for a checkbox. I mean something that will output a 1 or 0... thank you I was wondering if there's any common method for user management. I'm not talking about basic stuff like DB management stuff I'm talking about registering new users with captcha, validating email addresses, password resets, etc. I can work all this stuff out by hand but it seems rather large and very repetitious so I was wondering if there's guides out there to develop this or a common script? Dusting off my PHP skills after some time! How would I do this... Code: [Select] IF form was submitted THEN do some PHP stuff and do not show the form again ELSE display the form for the first time Is it as simple as wrapping my HTML inside an If-Then-Else? Debbie Hi, New to coding so pls bear with me.... I am running into a continual issue that wonder if there is a better way to handle it. When writing code that handles GET variables that have not been set I use the isset function with if statements to handle it, but my code looks like it is getting sloppy and I am having to repeat it a lot - for example: Every time I simply want to call a class / function that I want to pass avGET i have to do the following: Code: [Select] if (isset($_GET["filter"])){$theFilter = $pageination->filter($_GET["filter"]);} else {$theFilter = $pageination->filter();} Here is a copy of the class I have created (note sure if it works yet as not fully tested it) Code: [Select] class pageination { private $recordLimit=100; public function filter ($filter="") { if ($filter!=""){ $theFilter=" AND ".$filter; return $theFilter; } else { return $theFilter=""; } } private function pageCnt ($pageCntRst) { $pageCnt=intval($results[$pageCntRst]); return $pageCnt; } public function pageNmLnk () { echo 'Page: <a href="?pageStartListings=0&filter='. $_GET['filter'].'">1</a>'; } //This loops through every 100 pages public function pageNmLoop ($pageCnt) { for ($n=1; $n<=$pageCnt; $n++){ if ($n > $recordLimit) { break; } if ($n*$recordLimit==intval($_GET["pageStartListings"])){ $stylePg = 'style="border: 1px solid #aaaaaa; background-color: #CCCCCC; padding:3px; "> ' . $n+1 . '</a>'; } else{ $stylePg = ''; } echo '| <a href="?pageStartListings=' . $n*$recordLimit . '&filter=' . rawurlencode($_GET["filter"]) . ' " ' . $stylePg; } } } $pageination = new pageination (); ?> I use the GET a few times in the code and I have to write a lot of code around the isset and if statements to handle it all the time - thinking there must be a better way to do this or a function that can be built to test it? Any help is grateful in advance. Hi All. New at this, form is working perfect, then added recapthca, now it only handles recaptcha and not the form. not sure where the error is
|