다른 기능을 '동적으로'호출하는 재사용 가능한 PHP 함수를 만드는 데 도움이됩니다.
-
20-09-2019 - |
문제
MySQL의 관계형 DB와 Codeigniter와 함께 PHP에서 만든 일종의 CMS로 진지하게 무언가를 만들려고하는 것은 이번이 처음입니다.
나는 몇 가지 다수의 관련 테이블에 일부 데이터를 삽입 해야하는 부분에 왔습니다.
내 코드에서는 모든 것이 잘 작동하지만 (몇 분의 테스트만으로도) 재사용 가능한 기능을 만드는 데 도움이 필요합니다.
내 코드에 모든 것을 댓글을 달려고 했으므로 모든 설명이 거기에 있습니다 ...
<?php
function add(){
// This is what user posted in form.
// There are two input fields:
// name is always only one record
// country can be a single record or array separated with " | " characters
// I use CodeIgniter's $this->input->post instead of $_POST[]
$name = $this->input->post('name');
$countries = $this->input->post('country');
// Inserting data to first table
$data = array('firstName' => htmlentities($name)); // preparing array for inserting
$insert_name = $this->db->insert('names', $data); // inserting with CodeIgniter's help
$last_inserted_ID = $this->db->insert_id(); // getting last inserted ID
// Inserting data to second table
// Formatting of posted string of countries
// Users can post strings similar to this:
// "Austria"
// "Austria |"
// "Austria | "
// "Austria | Australia"
// "Austria | Australia |"
// "Austria | Australia | "
// and similar variations
// What I need here is clear array with country names
$separator = strpos($countries,"|"); // check for "|" character
if ($separator === FALSE){ // if there is no "|" character in string
$countries_array[] = $countries; // array is only one value (only one country)
} else {
$countries_array = explode(" | ", $countries); // explode my array
if (end($countries_array) == ""){ // if last item in array is ""
array_pop($countries_array); // eliminate last (empty) item
}
}
// Now, this is the part I think I will use lots of times.
// I would like to make this a separate function so I could use it in many places :)
// I would pass to that function few values and I would use one of them
// to call different functions in this same class.
// I guess I should pass data ($countries_array) and function names I wish to call?????? This is problematic part for my brain :))
// Check the comments below...
for ($i = 0; $i < sizeof($countries_array); $i++){
$insertIDS = array(); // this will be an array of IDs of all countries
$tempdata = $this->get_countries($countries_array[$i]); // query which looks if there is a country with specific name
// Right here, instead of calling $this->get_countries
// I would like to call different functions, for example
// $this->get_links($links_array[$i])
// or $this->get_categories($categories_array[$i])
// etc.
if(sizeof($tempdata) != 0){ // so, if a record already exists
foreach ($tempdata as $k => $v){
$insertIDS[] = $k; // insert those IDs in our array
}
} else { // and if a record does not exist in db
$this->add_country($countries_array[$i]); // add it as a new record...
// This is also one of the places where I would call different functions
// for example $this->add_link($links_array[$i])
// or $this->add_categories($categories_array[$i])
// etc.
$insertIDS[] = $this->db->insert_id(); // ...get its ID and add it to array
}
// Finally, insert all IDs into junction table!
foreach ($insertIDS as $idKey => $idValue){
$this->add_names_countries($last_inserted_ID, $idValue); // Another place for calling different functions
// example $this->add_names_links($last_inserted_ID, $idValue)
// etc.
}
}
}
?>
글쎄, 지금이 코드를 살펴보면, 나는 그 기능에도 그 형식 부분을 넣을 수 있다는 것을 알지만 지금은 그리 중요하지 않습니다 ...
도움을 주셔서 대단히 감사합니다 !!
해결책
이 작업을 수행하는 선호하는 방법은 사용하는 것입니다. 테이블 데이터 게이트웨이. 대신에
$this->db->insert('countries', $data);
데이터베이스의 각 테이블에 대한 클래스를 만듭니다. 각 테이블은 CRUD 로직을 클래스에 캡슐화합니다.
class Countries
{
$protected $_db;
public function __construct($db)
{
$this->_db = $db;
}
public function save(array $countries)
{
$this->db->insert('countries', $countries);
}
// ... other methods
}
또한 사용하는 것이 좋습니다 업무 이런 종류의 작업의 경우 모든 것이 함께 속해 있고 쿼리 중 하나가 실패한 경우 데이터를 삽입하고 싶지 않을 수 있습니다. Codeignitor가 거래를 처리하는 방법을 모르겠지만 기본적으로 다음과 같은 방식으로 수행해야합니다.
$this->db->startTransaction(); // like try/catch for databases
$countries = new Countries($this->db);
$countries->save($countryData);
$links = new Links($this->db);
$links->save($linkData);
// ...
if($this->db->commit() === false) { // returns true when no errors occured
$this->db->rollback(); // undos in case something went wrong
}
이것은 당신의 질문에 대답하지 않지만 함수를 동적으로 호출하는 방법 (call_user_func()
위에서 제안한 것처럼 코드가 훨씬 더 많이 유지 될 수 있습니다.
귀하의 질문은 모든 기능을 시퀀스로 실행하려는 경우 또는 사용자가 제출 한 내용에 따라 교환하려는 경우 약간 모호합니다. 첫 번째 경우 거래 접근법을 사용하십시오. 두 번째 경우에는 적절한 클래스를 인스턴스화하고 저장 메소드를 호출합니다.
다른 팁
당신의 요구 사항을 완전히 확신하지 못하지만 나는 당신이 call_user_func
:
function process($countries) {
// do stuff
}
$function_name = 'process';
call_user_func($function_name, $countries);
이렇게하면 국가 목록을 기반으로 함수를 동적으로 할당 할 수 있습니다.