Class for adding options to the site
Preface to the lesson
Working with CMS WordPress, I really liked the idea of options in plugins., which can be used as in the admin panel, and on the user side. These options can be placed as technical information during development (database connection data, store a list of custom fields, store options that apply to particular data types), and some static data that is displayed on all pages (address, phone, Name of the site, slogan). These options are very useful for displaying contact information., that don't change often, but they are often located in different parts of the code and it is very inconvenient to search for them.
From words to deeds
I think we have finished with the introduction and the first thing I will give you is the code of the class itself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
<?php class optionsClass { var $option; var $value; var $autoload; var $new_value; var $prefix; var $db; var $error; function __construct($db, $prefix){ // создает таблицу в базе даных с нужным префиксом, сразу после подключения класса if(!$db || !$prefix){ $this->error[] = 'Не хватает параметров'; exit; } $this->db = $db; $this->prefix = $prefix; $createTable = ' CREATE TABLE `'.$prefix.'_options` ( `option_id` bigint(20) unsigned zerofill NOT NULL AUTO_INCREMENT, `option_name` varchar(64) DEFAULT NULL, `option_value` longtext, `autoload` varchar(20) DEFAULT NULL, PRIMARY KEY (`option_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; '; $query = 'select * from `'.$prefix.'_options`'; $result = mysql_query($query , $this->db); if($result === false){ $result = mysql_query($createTable , $this->db); } } function get_option( $option, $default='' ){ // достаем опции из базы $query = "select option_value from ".$this->prefix."_options WHERE option_name='".$option."'"; $result = mysql_query($query , $this->db); $row = mysql_fetch_array($result); if($row['option_value']){ return $row['option_value']; }else{ $this->error[] = 'Опция не найдена'; return false; } } function add_option($option, $value, $autoload='yes'){ if($this->is_name_options($option) == false){ // Добавляем опции $query = "INSERT INTO ".$this->prefix."_options (option_name, option_value, autoload) VALUES ('".$option."', '".$value."', '".$autoload."')"; $result = mysql_query($query , $this->db); if(!$result){ $this->error[] = 'Не удалось добавиь опцию в базу данных'; }else{ $this->error[] = 'Опция ("'.$option.'" => "'.$value.'") добавлена в базу данных в базу данных'; } }else{ $this->error[] = 'Имя не уникально'; return false; } } function is_name_options($option_name){ // проверяем наицие опции в базе if(isset($option_name)){ $query = "select * from ".$this->prefix."_options WHERE option_name='".$option_name."'"; $result = mysql_query($query , $this->db); $row = mysql_fetch_array($result); if($row){ return true; }else{ return false; } }else{ $this->error[] = 'Опция не задана'; } } function update_option($option, $value){ // Обновляем опции if($this->is_name_options($option)){ $query = "update ".$this->prefix."_options SET option_value='".$value."' WHERE option_name='".$option."'"; $result = mysql_query($query , $this->db); if($result){ $this->error[] = 'Опция '.$option.' обновлена'; }else{ $this->error[] = 'Опция '.$option.' не обновлена'; } }else{ $this->error[] = 'Нет такой опции ['.$option.'] в базе'; } } function delete_option($option){ // удаляем опции if($this->is_name_options($option)){ //echo $option; exit; $query = "delete from ".$this->prefix."_options WHERE option_name='".$option."'"; //echo $query ; $result = mysql_query($query , $this->db); if($result){ $this->error[] = 'Опция '.$option.' удалена'; }else{ $this->error[] = 'Опция '.$option.' не удалена'; } }else{ $this->error[] = 'Нет такой опции ['.$option.'] в базе'; } } function load_alloptions(){ // вывести на экран все опции $query = "select option_name, option_value from ".$this->prefix."_options"; $result = mysql_query($query , $this->db); while($row = mysql_fetch_array($result)){ echo '[ '.$row['option_name'].' ] => [ '.$row['option_value'].' ]<br />'; } } function log(){ // лог операций и ошибок if($this->error){ echo '<pre>'; print_r($this->error); echo '</pre>'; } } } ?> |
This is such a difficult class., let's look at all its methods in order.
Class constructor - checks, does the database have an options table, if she is not, then independently creates this table. The constructor accepts a database connection variable $db and a table prefix variable $prefix. If there are no $db or $prefix variables, then an error message is written to the $error property and the program stops.
Method get_option() needed to display one option that is already in the database. Here is the usual selection, think, if you work with OOP, then you can no longer talk about it.
Method add_option($option, $value) needed to add new options to the database, if an option with the specified name already exists, then to the property $this->error a message is added, which the developer can display for himself or for site visitors using the method log().
Method is_name_options() helps to check, is there an option with the suggested name in the options table.
Method update_option() updates data in already existing options. Accepts 2 required parameters $option and $value (option name and value).
class method delete_option() needed to remove unnecessary options, if it exists in the database. The option is checked and if found, then removed from the database by name.
Method load_alloptions() designed to display all options on the screen, this function is needed solely for viewing options by the developer.
About method log() we already said, this method is for outputting all messages, that got into the property array $this->error.
Working with the Options Class
Now, when we have considered all the methods, we can smoothly move on to working with our class.
Since the class works for us through the database, then first we need to create it and connect, and the table will be created by our class.
1 2 3 4 5 6 |
$db = mysql_connect('localhost', 'db', 'wp-admin'); if (!$db) { die('Could not connect: ' . mysql_error()); } mysql_select_db( 'db-name', $db ); |
Next, we connect our class and try to use it:
1 2 3 4 5 6 7 8 9 10 11 12 |
include './optionsClass.php'; $prefix = 'cl'; $obj = new optionsClass($db, $prefix); $obj->add_option('optionsName',12); //$obj->update_option('optionsName',13); //$obj->delete_option('optionsName'); $obj->load_alloptions(); $opt = $obj->get_option('optionsName'); echo $opt; $obj->log(); mysql_close($db); |
Play around with the class methods and try adding new options using the methods, display them on the screen, update data in options, remove options. Be sure to try displaying messages using the method log().
That's the whole general overview of the class, I think you'll figure it out. To work with the example, you must enter new data to connect to the database. I put the class itself in a file, so that you don't get errors while copying, but be sure to understand its operation before using.
If you find inaccuracies, write us in the comments and we will try to fix them.
/*
- Basic web design course;
- Site layout;
- General course on CMS WordPress and continuation of the course on template development;
- Website development in PHP.