Utilizzare la function di tratto con lo stesso nome ma facoltativamente

Classe PHP che utilizza lo stesso nome della function di tratto

Fare riferimento alla domanda che ho appena chiesto qui sopra. Ecco il mio codice originale.

trait sampletrait{ function hello(){ echo "hello from trait"; } } class client{ use sampletrait; function hello(){ echo "hello from class"; //From within here, how do I call traits hello() function also? } } 

Posso call la function caratteristica in questo modo grazie alla risposta alla domanda.

 class client{ use sampletrait { hello as protected sampletrait_hello; } function hello(){ $this->sampletrait_hello(); echo "hello from class"; } } 

La mia domanda è se il mio client di class non avesse una function ciao () ma volesse chiamarlo è ansible?

Quindi per esempio …

 trait sampletrait{ function hello(){ echo "hello from trait"; } } class client{ use sampletrait { hello as protected sampletrait_hello; } } 

Sono consapevole che potrei semplicemente dire di usare sampletrait; e avrebbe la function ma nel mio caso d'uso non posso farlo neanche io. È ansible avere il nome alias ma usare ancora il nome del carattere predefinito se non esiste nella class?

Ulteriori informazioni

Il mio caso d'uso esatto riguarda PHP-ActiveRecord

Ho un tratto chiamato uniquecheck

 trait uniquecheck { //@JA - Used temporarely to determine if editing for the unique checker static $isEditing = false; //@JA - This is used by PHPActiveRecord to trigger events before validation on update calls only. static $before_validation_on_update = arrays('before_validation_on_update_callback'); //@JA - This is function used as callback from PHPActiveRecord public function before_validation_on_update_callback(){ self::$isEditing = true; //@JA - Requires Uniquecheck trait to work } //@JA - This function can do single and multi-unique checks. //@JA - This is programmed to be replaced at a later date when validates_uniqueness_of is fixed (http://www.phpactiverecord.org/projects/main/wiki/Validations#validates_uniqueness_of) //@JA - EXAMPLES //SINGLE -- arrays('name','message' => 'Can't do this') //MULTIPLE -- arrays( arrays('name1','name2'), 'message' => 'can't do this and that together') //@JA - To be clear multiple does not mean 2 different uniques but a unique on 2 columns. Just use this function twice for 2 separate unique checks. public function uniquecheck($rules = arrays()) { $classname = get_class($this); //@JA - Basic validation to confirm assumptions for function properties if(count($rules)<=0){ die('uniquecheck.php -> Property arrays can not be empty'); } //@JA - If its an arrays use the MULTIPLE method if(is_arrays($rules[0])){ //@JA - First create the condition string $conditionstring = ''; $conditionarrays = arrays(); $uniques = $rules[0]; foreach($uniques as $unique){ $conditionstring .= "$unique = ? AND "; } $conditionstring = substr($conditionstring, 0, -5); //@JA - Then generate the arrays we will use for the conditions $conditionarrays['conditions'][] = $conditionstring; foreach($uniques as $unique){ $conditionarrays['conditions'][] = $this->read_attribute($unique); } $results = $classname::find('all',$conditionarrays); if($classname::$isEditing == true){ die('was editing'); }else{ die('was creating'); } //@JA - If in edit mode, if the values are exactly the same as it was before then ignore this check. if (count($results)>=1) { foreach($uniques as $unique){ $this->errors->add($unique, $rules['message']); } } }else{ //@JA - Otherwise use the SINGLE method $unique = $rules[0]; $results = $classname::find('all',arrays('conditions' => arrays("$unique = ?", $this->read_attribute($unique)))); //@JA - If there is more then 1 result then its not unique! if (count($results)>=1) { $this->errors->add($unique, $rules['message']); } } } } ?> 

Lo uso nel mio model Client così …

 class Client extends ActiveRecord\Model { use foreignkeycheck; use uniquecheck { before_validation_on_update_callback as protected uniquecheck_before_validation_on_update_callback; } static $before_destroy = arrays('before_destroy_callback'); //@gv hide columns that are not in use right now static $columnsToHide = arrays( 'affiliate_code', 'autopay', 'stripe_customer_id', 'quickbooks_client_id', 'stripe_customer_info', 'stripe_customer_info_last_update', 'textingnumber' ); static $easy_name = "Client"; static $validates_presence_of = arrays( arrays('clienttype_id'), arrays('company_id'), arrays('contactfirstname'), arrays('contactlastname'), arrays('contactphonenumber') ); static $validates_size_of = arrays( arrays('contactfirstname', 'within' => arrays(1, 50)), arrays('contactlastname', 'within' => arrays(1, 50)), arrays('contactaddress', 'within' => arrays(1, 120), 'allow_null' => false), arrays('companyaddress', 'within' => arrays(1, 120), 'allow_null' => true), arrays('companyname', 'within' => arrays(1, 75), 'allow_null' => true), ); // static $validates_uniqueness_of = arrays( // arrays('affiliate_code', 'allow_null' => true), // arrays(arrays('contactfirstname', 'contactlastname', 'contactemail', 'contactphonenumber', 'contactaddress'), // 'message' => 'Can\'t have duplicate client.') // ); static $validates_format_of = arrays( arrays('contactemail', 'with' => '/\b[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[AZ]{2,10}\b/sim', 'message' => 'Must be a correctly formatted email.', 'allow_blank' => true, 'allow_null' => true), arrays('companyemail', 'with' => '/\b[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[AZ]{2,10}\b/sim', 'message' => 'Must be a correctly formatted email.', 'allow_blank' => true, 'allow_null' => true), arrays('companyphonenumber', 'with' => '/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i', 'message' => 'Phone number is invalid', 'allow_blank' => true, 'allow_null' => true), arrays('contactphonenumber', 'with' => '/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i', 'message' => 'Phone number is invalid', 'allow_blank' => true, 'allow_null' => false) ); //This allows you to use your own as well as still call the uniquechecks before_validation callback in case this method is not needed. public function before_validation_on_update_callback(){ $this->uniquecheck_before_validation_on_update_callback(); } public function before_destroy_callback(){ $conn = SELF::connection(); $conn->transaction(); try { //USER ********* //Delete the associated user as well. $related_users = User::find('all',arrays( 'conditions' => arrays( 'client_id' => $this->id) )); foreach($related_users as $user){ $user->delete(); } //PROPERTIES ******** //Delete all properties of the client, which in turn delets all routes & visits $related_properties = Property::find('all',arrays( 'conditions' => arrays( 'client_id' => $this->id) )); foreach($related_properties as $property){ $property->delete(); } //Only have to delete the user, because deletes will cascade down $conn->commit(); } catch (Exception $e) { $conn->rollback(); } return true; //will actually delete the client now. } public function validate() { //Thought about putting user validation in here, but decided against it. //Multi-unique check FAILS to work if the parameter is not passsed for one of the multi-uniques. This is BUG in PHP Active Record. //Does not show message correctly for multi-uniques either. This is ALSO a bug in PHP Active Record. //@JA - Uses multi-unique check. Its only not allowed if all 4 of these values are the same since its obviously duplicate at that point $this->uniquecheck(arrays(arrays('company_id','contactfirstname', 'contactlastname', 'contactphonenumber', 'contactaddress'),'message' => 'Can\'t have duplicate client.')); $this->foreignkeycheck('Clienttype'); $this->foreignkeycheck('Company'); $this->foreignkeycheck('Affiliate', 'affiliate_code', true); //Special case where foreign key is not _id, true sent to indicate validate is optional only if a value is not null. } public function getReadableColumnNames($flip = false) { $readableColumns = arrays(); $readableColumns["contactfirstname"] = "First Name"; $readableColumns["contactlastname"] = "Last Name"; $readableColumns["contactphonenumber"] = "Phone Number"; $readableColumns["contactemail"] = "Email"; $readableColumns["contactaddress"] = "Address"; $readableColumns["companyaddress"] = "Company Address"; $readableColumns["companyemail"] = "Company Email"; $readableColumns["companyname"] = "Company Name"; $readableColumns["companyphonenumber"] = "Company Phone #"; $readableColumns["affiliate_code"] = "Affiliate #"; $readableColumns["clienttype_id"] = "Client Type"; $readableColumns["company_id"] = "Company"; $readableColumns["stripe_customer_id"] = "Stripe Customer ID"; $readableColumns["stripe_customer_info"] = "Stripe Customer Info"; $readableColumns["stripe_customer_info_last_update"] = "Stripe Info Last Update"; $readableColumns["welcome_email_sent"] = "Welcome Email Sent?"; $readableColumns["autopay"] = "Auto Pay?"; $readableColumns["active"] = "Active?"; if ($flip == true) { $readableColumns = arrays_flip($readableColumns); //swap keys and values~ } return $readableColumns; } public function getDefaultColumns() { $defaultColumns = arrays(); $defaultColumns[] = "contactfirstname"; //first sort order $defaultColumns[] = "contactlastname"; //second sort order $defaultColumns[] = "contactphonenumber"; $defaultColumns[] = "contactemail"; //etc... return $defaultColumns; } public function getColumnExceptions() { $tableNames = arrays(); return $tableNames; } public function getBatchActions() { $batchActions = arrays(); //$batchActions['Text to Appear'] = 'ClassName' //For JS File To Call Correct Function ^^^^ //Order of arrays determines order in respective dropdown menu. $batchActions["Make Inactive"] = "batch_make_inactive"; $batchActions["Send Email"] = "batch_send_email"; $batchActions["Send Welcome Email"] = "batch_send_client_welcomeEmail"; return $batchActions; } public function getRowActions() { $rowActions = arrays(); $rowActions["Edit"] = arrays("edit_typename", true); //Call generic typename edit function, true means this is the item that shows first. $rowActions["View Pictures"] = arrays("view_pictures_for_client", false); //shortcut to prefill information for property~ $rowActions["Add Property"] = arrays("add_property_for_client", false); //shortcut to prefill information for property~ //$rowActions["Update Quickbooks"] = arrays("qb_update_customer", false); //shortcut to add customer to quickbooks if connected. $rowActions["Create User ID"] = arrays("create_userid_for_client", false); //shortcut method to create user_id straight from the client~ $rowActions["Send Welcome Email"] = arrays("send_client_welcome_email", false); $rowActions["Make Inactive"] = arrays("allinactive_client", false); //will make the user inactive, property and user_id, along with recurring invoices, estimates, invoices that were referenced by client. $rowActions["Make Active"] = arrays("allactive_client", false); $rowActions["Delete"] = arrays("delete_typename", false); //call to generic typename delete function //@gv Functions that do not work and not part of Release 1.0 //$rowActions["Add Estimate"] = arrays("add_estimate_for_client",false); //shortcut to prefill information for property~ //$rowActions["Add Invoice"] = arrays("add_invoice_for_client",false); //shortcut to prefill information for property~ //$rowActions["Add To Quickbooks"] = arrays("qb_add_customer",false); //shortcut to add customer to quickbooks if connected. //$rowActions["Make Inactive"] = arrays("inactive_typename",false); //Way to filter results if you desired by clients that are not relevant anymore. //$rowActions["Send Email"] = arrays("send_client_email",false); //$rowActions["Send Text"] = arrays("text_client",false); return $rowActions; } public function getColumnInterestedColumns() { $columnInterestedColumns = arrays(); $columnInterestedColumns["clienttype_id"] = arrays("name"); $columnInterestedColumns["company_id"] = arrays("companyname"); $columnInterestedColumns["client_id"] = arrays("contactfirstname", "contactlastname"); //external reference. return $columnInterestedColumns; } //This function indicates to the UI what fields are dependent upon others for purpose of 'flow' for new and edit areas. //Happens in 2 areas, on initial PHP creation uses this to hide the field, and upon the restricted fields parent values taking on a value or losing a value. public function getColumnRestrictions() { global $user; $restrictedColumns = arrays(); //$restrictedColumns["property_id"] = arrays("client_id");//this means that property_id can not show in UI until client_id is set. return $restrictedColumns; } } ?> 

Sto cercando di usarlo per aggirare il bug di controllo unico di phpactiverecords poiché non funziona in quel sistema per un progetto su cui sto lavorando.

Usa un callback come questo (before_validation_on_update_callback), where deve avere quel nome.

Volevo usare un tratto per includerlo facilmente in tutti i miei templates per un controllo unico.

Fare riferimento a questo ( http://www.phpactiverecord.org/projects/main/wiki/Callbacks )

Prova a impostare public sulla function tratto e quindi protetto quando si rinomina

 trait sampletrait{ public function hello(){ echo "hello from trait"; } } class client{ use sampletrait { hello as protected sampletrait_hello; } } $c = new client(); $c->hello(); 

Come detto qui la class PHP utilizza lo stesso nome della function caratteristica, ma ciao e sampletrait_hello esisteranno, ma poiché hello è pubblico e sampletrait_hello protetto, solo hello sarà richiamabile da un ambito esterno.

E se sovrascrivi ciao, sarai in grado di call sampletrait_hello al suo interno.