PHP - Creating A Digital Twin Of An Object
I have a class which is injected with various objects and those objects contain other objects where some of them contain content from various APIs, user data, etc. I would like to obtain a persistent copy of one of these sub-objects so I may modify my class and test it without having to recreate it each time. Anyway existing tools to automate this process? One thought is using reflection to access all the properties and recursively go over each which somehow creates some JSON file which can act as the input to some factory class to create the same instance? Or maybe some custom function which somehow creates some executable which reflects the bits and bytes in the PHP object? Thanks Similar TutorialsHi, I am converting XML to DB and was wondering is it bad XML structure to have twin siblings (or triplets or identical siblings in general), what I mean is: eg: <email> <to> <toFirstName>John</toFirstName> <toLastName type="common">Smith</toLastName> </to> <to> <toFirstName>Jack</toFirstName> <toLastName type="unique">Dravisone</toLastName> </to> </email> Any help much appreciated! Hi, I have decided to try and write some OO php. I have a simple class with one function. I am trying to instantiate an object of that class using the new operator but get an error. Parse error: syntax error, unexpected T_OBJECT_OPERATOR in C:\wamp\www\School\addcourse.php on line 38 Code: [Select] <?php $CDBController = new CMasterDataController; //THIS IS LINE 38 CMasterDataController->PerformQuery("SOME SQL HERE"); ?> I am including the file that contains this class (CMasterDataController) in this file (addcourse.php). The version of PHP i am using is 5.3.8. Does anybody know what I am missing? Thanks, Joe Hello everyone, I have a PHP Laravel CRUD application I made where I am using MVC style. I have controllers views and models. My database migration is made and my table in the database is made with php artisan migrate. I am using php 7.3 and laravel 5.8. On my create view I go to create a single object in my database and my errors are thrown saying nothing in text box (no input) If I comment out the errors then just I click my submit button and nothing happens nothing is entered into my db. I have looked at many different crud examples and I am not sure why my object isn’t being created. Here is what I have
//view create @section('main') <section id="section-content" class="text-center"> <div class="container contentdiv rounded"> <div class="row"> <div class="col-md-12"> <div class="pb-2 mt-4 mb-2 border-bottom clearfix"> <h2>Create Contact</h2> </div> <div > <a class="btn btn-success" href="{{route('contacts.index')}}">Back</a> </div> </div> <!-- <div class="col-md-10 mx-auto"> @if($errors->any()) <div class="alert alert-danger"> <ul> @foreach($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div><br /> @endif </div> --> <div class="row"> <div class="col-md-10 mx-auto mt-3"> <form method="POST" action="{{ route('contacts.store') }}"> @csrf <div class="form-group row"> <label for="txtfn" class="col-sm-3"><b>First Name:</b></label> <div class="col-sm-9"> <input type="text" class="form-control" name="txtfn" id="txtfn"/> </div> </div> <div class="form-group row"> <label for="txtln" class="col-sm-3"><b>Last Name:</b></label> <div class="col-sm-9"> <input type="text" class="form-control" name="txtln" id="txtln"/> </div> </div> <div class="form-group row"> <label for="txtem" class="col-sm-3"><b>Email:</b></label> <div class="col-sm-9"> <input type="text" class="form-control" name="txtem" id="txtem"/> </div> </div> <button type="submit" class="btn btn-primary">Create Contact</button> </form> </div> </div> </div> </section> //controller namespace App\Http\Controllers; use App\Contact; use Illuminate\Http\Request; class ContactController extends Controller { public function store(Request $request) { $request->validate([ 'first_name' => 'required', 'last_name' => 'required', 'email' => 'required' ]); $contact = new Contact([ 'first_name' => $request->get('first_name'), 'last_name' => $request->get('last_name'), 'email' => $request->get('email'), 'job_title' => $request->get('job_title'), 'city' => $request->get('city'), 'country' => $request->get('country') ]); $contact->save(); return redirect('/contacts')->with('success', 'Contact saved!'); } public function index() { $contacts = Contact::all(); return view('contacts.index', compact('contacts')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('contacts.create'); } // model namespace App; use Illuminate\Database\Eloquent\Model; class Contact extends Model { protected $fillable = [ 'first_name', 'last_name', 'email', 'city', 'country', 'job-title' ]; } My env is setup correctly I just don’t get the not creating object. Hi there, I am just wondering which way is the correct one if you want to create object properties/attribute dynamically at run time using magic method __set(), __get(), for example: class Foo{ public $data = array(); public function __set($name,$value){ $this->data[$name] = $value; } public function __get($name){ if ( isset($this->data[$name]) ){ return $this->data[$name]; } } } Or using the below way class Foo{ public function assign(array $data){ foreach($data as $key => $value){ $this->$key = $value; } } } I just encountered the second way in many places and I am totally confused . Is the __set() method called implicitly by the PHP engine in the second way or what? how come this is considered as a valid code ? your usual help is appreciated Hello there! I am new to php and working on registration system using biometric authentication. I need to implement digital personna integration with php. I have searched for so many times on internet but could not found any relevant information. First i thought that we scan our finger and the device will generate the hash code easily and display on focus area(input field). But it does not. So kindly help me to solve this problem Thanks!
Hey all, I want to have an object that has a property which is an object containing instances of other objects. I try this: Code: [Select] class Blog extends Posts { public $has_posts; public function __construct($a,$b,$c){ $has_posts = (object) array_merge((array) $a, (array) $b, (array) $c); } } class Posts { public $b; public function __construct($b){ $this->b = $b; } } $post1 = new Posts(1); $post2 = new Posts(2); $post3 = new Posts(3); $blog = new Blog($post1,$post2,$post3); var_dump($blog->has_posts); //null foreach($blog->has_posts as $post){ //Invalid argument supplied for foreach() echo $post->b; } But as you see, has_posts is null, not an object containing other objects. Thanks for response. I have a Soup object in a Bowl object in a Microwave object. The Microwave object has the methods: receiveItem(Bowl $b) cookItem(???) I want the Microwave to be able to set the Soup->temperature but I'm not how to do that? Make sense? TomTees I made a small script and it says that my database object isn't an object. I connect to my pdo database via: <?php try { $db = new PDO("mysql:host=localhost;dbname=database", "root", "root"); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo $e->getMessage(); } ?> The error I get is Code: [Select] Notice: Undefined variable: db in /Users/JPFoster/Sites/jobiji_sandbox/extensions/tasks.php on line 21 Fatal error: Call to a member function query() on a non-object in /Users/JPFoster/Sites/jobiji_sandbox/extensions/tasks.php on line 21 here's where the error is $grabber = $db->query('SELECT * WHERE user_id =' . $userid); $grabber->setFetchMode(PDO::FETCH_OBJ); while ( $row = $grabber->fetch() ){ $display = '<div>Task Name: ' . $row->name .'</div>'; $display .= '<div>Task Details: <p>'. $row->details .'</p></div>'; //$display .= '<div>'. $this->checkifDone($row->task_status) .'</div>'; $display .= '<div>Task Due: '. $row->task_due . '</div>'; echo $display; } could anyone tell me where this issue is originating I followed a fairly simple tutorial that didn't seem to work. Thanks! Ok. So, I'm trying to retrieve the id value from an object. Here is the code I have that works so far: Code: [Select] $object = 'object'; $koid = $this->$object; echo '<pre>'; print_r($koid); echo '</pre>'; and this is what is returns: Code: [Select] Order Object ( [id:protected] => 5 [stand_by:protected] => test [problem:protected] => test ) what do I need to do to make $koid equal the id value (5 in this case)? I am trying to get elements in a dom object to display and manipulate however i cant seem to get them all out: This is the feed: <TransactionList> <TransactionID>507821041</TransactionID> <TransactionDate>2012-03-12T13:23:00+00:00</TransactionDate> <MerchantID>547</MerchantID> <MerchantName>The High Street Web</MerchantName> <ProgrammeID>1865</ProgrammeID> <ProgrammeName>THE HIGHSTREET WEB</ProgrammeName> <TrackingReference>{CLICKID}</TrackingReference> <IPAddress>82.34.245.167 </IPAddress> <SaleValue>0.0000</SaleValue> <SaleCommission>0.0400</SaleCommission> <LeadCommission>0.0000</LeadCommission> </TransactionList> However i am trying to get more than 1 tag but i cant seem to get it right. This is my code: <?php $dom = new DomDocument; $dom -> load ( "http://xyz.com" ); $tracking = $dom -> getElementsByTagName( "TrackingReference" ); //$com = $dom -> getElementsByTagName( "SaleCommission" ); $c1 = 0; foreach( $tracking as $code ) { #echo $code -> textContent.'<br>'; $tcode = $code -> textContent; $tcom = $com -> textContent; //$com = $dom -> getElementsByTagName( "SaleCommission" ); if ($tcode !="") { $remove_it = '{CLICKID}'; $tcode = str_replace($remove_it, "", $tcode); echo $tcode.' VALUE '. $com .'<br>'; $c1 ++; } } echo 'Total Count: '.$c1; ?> Please can someone help and tell me where im going wrong! I've been trying to solve this issue for so long now.. I believe I'm close, but it's just the last part that I can't figure out how to solve.. I have a set of parsers and a controller. each parser is in it's own object named like Parsers_Imdb_Imdb.. What I want now is to be able to do this Code: [Select] $parse = new Parsers; $imdb = $parse->Imdb->get_info('some random info'); So far I've managed to get into the Imdb parser object, but I 'm not able to grab the method. parsers.php Code: [Select] class Parsers { function __construct() { } public function Imdb() { new Parsers_Imdb_Imdb; } } imdb.php Code: [Select] class Parsers_Imdb_Imdb extends Parsers { function __construct() { parent::__construct(); } public function get_info() { echo "get_info()"; } } I've got a __autoload() to solve the class declaration.. Could anyone please help me out with this? Thanks in advance ok that works fine can i store a object tag in the db and show that same obj tag in the div ill paste my code but its hard coded <div id="resultmedia"> <object width="640" height="385"> <param name="movie" value="http://www.youtube.com/v/vFagaB9M6nQ?fs=1&hl=en_GB"></param> <param name="allowFullScreen" value="true"></param> <param name="allowscriptaccess" value="always"></param> <embed src="http://www.youtube.com/v/vFagaB9M6nQ?fs=1&hl=en_GB" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="155" height="131"> </embed></object> hello all, I am new to php, and getting better using the object oriented approach. I have been a procedural programmer for several years, with a limited exposure to OOP. I have a question about pulling two values from an object. the following code is an excerpt from a class form. function getstocklist($currentcount){ $transactions = $currentcount['count']; $current = mysql_query("SELECT * FROM current_positions WHERE positiontype = 'long' OR positiontype = 'short'"); $tickers = ''; while ($stock = mysql_fetch_array($current)){ $tickers .= $stock['positionticker'] . ','; $stockList[] = array( 'shares' => round(($stock['positioncost']/$stock['positionprice']),0), 'date' => date("m/d/Y G:i:s", $stock['positiontime']-(45*60)), 'ticker' => $stock['positionticker'], 'type' => $stock['positiontype'], 'price' => $stock['positionprice'], ); } return($tickers); } I would like to get both the value of $tickers and the array $stockList. I am not sure how to proceed. any suggestions would be greatly appreciated. Thanks Kansas Hi I have a login script which goes at the top of several pages in my site. It works fine but I am trying to save some coding and re-writing out my script at the top of each of the pages. Instead I have made a page called login.php and put all of the code for the script in there. Looks like this.... <?php //login script if(isset($_POST['log'])) { $emaillog = stripslashes($_POST['emaillog']); $passwordlog = stripslashes($_POST['passwordlog']); $emaillog = mysql_real_escape_string($_POST['emaillog']); $passwordmd5 = md5($passwordlog); //generate random session id which i want to follow the user round the site! $CheckUser = "SELECT * FROM members WHERE email='".$emaillog."' AND password='".$passwordmd5."'"; $userDetails2 = mysql_query($CheckUser); $userInfo = mysql_fetch_array($userDetails2); $count = mysql_num_rows($userDetails2); if($count != 0) { $_SESSION['memberID'] = $userInfo['memberID']; $_SESSION['accesslevel']= $userInfo['accesslevel']; $_SESSION['email']= $userInfo['email']; //add an id that will be carried throughout the user until the session is destroyed function getUniqueCode2($length2 = "") { $code2 = md5(uniqid(rand(), true)); if ($length2 != "") return substr($code2, 0, $length2); else return $code2; } $randomKey = getUniqueCode2(25); $_SESSION['key'] = $randomKey; //the user must have an access level of 2, before they can login if($_SESSION['accesslevel']=='2') $url = "loggedin/index.php"; header("Location: ".$url.""); $success = '1'; } else { $success = '0'; $logged = "incorrect login details" or die(mysql_error()); } //now we need to update the login table to reflect a login if($success =='1'){ $time = date("Y-m-d h:m:s"); $qupdate_mem_logins = "INSERT INTO logindetails (`email`,`time`) VALUES ('".$emaillog."','".$time."')"; $rupdate_mem_logs = mysql_query($qupdate_mem_logins) or die(mysql_error()); ?> Now on the index page how do I reffer to this login script when someone fills in the form At the minute I have the following code but it is not checking or running anything. <?php //login script if(isset($_POST['log'])) { include('login.php'); } } ?> Hi everyone, It was recommended that I should make the switch from using procedural code to object oriented code with pdo for queries and such. So, I have been doing some reading on both topics, but am finding it rather hard to wrap my head around. I managed to get a PDO query to work with the help of a tutorial that I found online. My next step is to create an object oriented member registration class. I was wondering if anyone on here could provide any advice as far as the setup goes. I will want my member class to be able to: 1) connect to db 2) gather, validate, and send user data to payment processor 3) receive postback data, insert into database, and notify new member. I have already created these functionalities for other websites using procedural coding so once I get pushed in the right direction I should be find to add the other functionalities, which will include 4) Logging a member in 5) Logging a member out 6) Update member information 7) Change password Forgot password 9) Cancel membership Below is my snippet of PDO code that I wrote. Let me know if you guys would do anything differently. I really appreciate your help in this. Code: [Select] <?php // DECLARE DATABASE CONNECTION VARIABLES // $host = 'localhost'; $database = 'database'; $username = 'user'; $password = 'password'; // CONNECT TO DATABASE // try { $connect = new PDO("mysql:host=$host;dbname=$database", $username, $password); } catch(PDOException $e) { echo $e->getMessage(); } $sql = "SELECT siteInfoPage, siteInfoKeywords, siteInfoDescription FROM siteInfo WHERE siteInfoPage = '$page'"; // FETCH INTO A PDOStatement OBJECT // $query = $connect->query($sql); // ECHO THE NUMBER OF COLUMNS // $data = $query->fetch(PDO::FETCH_OBJ); // ASSIGN TO VARIABLES $page_title = $data->siteInfoPage; $keywords = $data->siteInfoKeywords; $description = $data->siteInfoDescription; // CLOSE THE DATABASE CONNECTION // $connect = null; ?> New to classes, basic understanding of procedural. I am trying to echo rows from the data base using PDO. Here is the code: Code: [Select] <div id="admin"> <form method="POST" action="categoryAdmin.php"> <table> <tr><th bgcolor="#EEEEEE">Cat Id</th> <th bgcolor="#EEEEEE">Title</th> <th bgcolor="#EEEEEE">Description</th> </tr> <?php global $dbh; $sql = "SELECT * FROM categories"; $sth = $dbh->prepare($sql); $sth-> execute(); print_r($sth); $result = $sth->fetchAll(PDO::FETCH_ASSOC); print_r($result); while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {echo "<tr><td>$row[0]<td><td>$row[1]<td><td>$row[2]<td><tr>\n";} ?> <tr><td><input type="text" name="CatId" size="15" maxlength="10"></td> <td><input type="text" name="CatTitle" size="40" maxlength="130"></td> <td><input type="text" name="CatDesc" size="45" maxlength="200"></td> </tr> </table> <input type="hidden" name="addRecord" value="1"> <input type="submit" name="submit" value="Add Category"> </div> print_r($sth); shows: PDOStatement Object ( [queryString] => SELECT * FROM categories ) print_r($result); shows: Array ( => Array ( [categoryId] => Fitness [title] => Sholder Guy [description] => Fix that sholder and more ) ) fatal error: Call to a member function fetchAll() on a non-object in /home/... the line in question is the while loop. I am not sure what to pass it with reguards to PDO. Thanks - AL I have this SimpleXMLElement Object and I can't echo out any attribute. In this example I am only showing you one SimpleXMLElement Object of the entire result set just for brevity. Here is the code that loops through the results: foreach($oXML->links->link as $o){ echo "<pre>";print_r($o);echo "</pre>"; } SimpleXMLElement Object ( [advertiser-id] => 2860239 [advertiser-name] => Amber Alert GPS [category] => Array ( [0] => children [1] => children ) [click-commission] => Array ( [0] => 0.0 [1] => 0.0 ) [creative-height] => Array ( [0] => 0 [1] => 0 ) [creative-width] => Array ( [0] => 0 [1] => 0 ) [language] => en [lead-commission] => SimpleXMLElement Object ( ) [link-code-html] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [link-code-javascript] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [description] => 20% discount of Amber Alert GPS Child Locator Device when using "Amber2" Promo Code. [destination] => http://www.amberalertgps.com [link-id] => 10745524 [link-name] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [link-type] => Text Link [performance-incentive] => false [promotion-end-date] => SimpleXMLElement Object ( ) [promotion-start-date] => SimpleXMLElement Object ( ) [promotion-type] => coupon [relationship-status] => joined [sale-commission] => 30.00% [seven-day-epc] => N/A [three-month-epc] => 2.66 ) I try to do this but it doesn't work: foreach($oXML->links->link as $o){ echo $o['advertiser-id']; } # I also tried this: foreach($oXML->links->link as $o){ echo $o->advertiser-id; } How do you echo the values? I'm curious if anyone has information on how much overhead there is with creating an object in PHP. I've tried finding some benchmarks but haven't really been able to find anything solid to use for reference. Also, when dealing with objects what optimizations can be done to improve performance. I ask because my project I've been working on is entirely OO. Everything, including views, are objects (though their state and behaviour is really just the model they're representing and a show() function that has the HTML used to display the model). This makes development very easy and clean but I'm trying to figure out how much of a difference I can expect in production and in what ways I can limit any negative side effects. What things could be cached, and what things can't? For example, is it possible to cache the class definition without caching instances of that definition (since they'd be different from page view to pageview)? Would that be helpful. Any pointers would be great. I haven't had a lot of time with performance tweaking so I'm not sure of any known pitfalls. I know objects and function calls use a bit more overhead but I've never found out how much more. Thanks in advance. I've been getting this error message: Trying to get property of non-object in /application/controllers/index.php on line 37 Here is line 37 $this->view->title = $pageInfo[0]->title; any help would be much appreciated. I have been trying to access an stdClass I can't. This stdClass gets returned from a method in a class . below the query is right all I want to do is put admi into a session var but I can't seem to access the obj. I can print_r and it displays. I am sure that it is easy. being new to PDO I am getting lost at times. Any help would be greatfully recieved Code: [Select] stdClass Object ( [Admin_Level] => admi ) |