Тип топика

Я уже писал здесь о том что было бы хорошо добавить возможность динамически определять новые типы топиков.
Есессно что специалистов тута много но на всяк случай:
prefix_topic:
`topic_type` enum('topic','link','question') NOT NULL DEFAULT 'topic' =>
`topic_type_id` int(11) NOT NULL DEFAULT '0'


prefix_topic_type (Новая):

`topic_type_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`topic_type` varchar(20) unsigned NOT NULL AUTO_INCREMENT,

6 комментариев

avatar
Вы молодец. Наверное это вполне логичный шаг к универсализации и расширению :)
avatar
Могу выложить патч которые реализует эту возможность. Но нужны добровольцы чтоб потестить у себя просто не смогу протестить ВСЕ функции
avatar
Здесь есть патч к текущей ревизии.
Очень НЕ РЕКЕМЕНДУЮ ставить на боевой сайт
Ошибки есессно будут прошу писать сюда.
П.С. файл upd.sql должон преобразовать БД к новому виду не затрагивая старый формат
Index: classes/modules/topic/mapper/Topic.mapper.class.php
===================================================================
--- classes/modules/topic/mapper/Topic.mapper.class.php	(revision 1053)
+++ classes/modules/topic/mapper/Topic.mapper.class.php	(working copy)
@@ -17,6 +17,22 @@
 
 class ModuleTopic_MapperTopic extends Mapper {	
 		
+	public function TopicTypeName2Id($oTopicName) {
+		$result = 0;
+		$sql = "SELECT topic_type_id FROM ".Config::Get('db.table.topic_type')." WHERE topic_type_name=?" ;
+		if($aRows = $this->oDb->select($sql,$oTopicName)) {
+			$result = $aRows[0]['topic_type_id'];
+		}
+		return $result;
+	}
+	public function TopicTypeId2Name($oTopicId) {
+		$result = "topic";
+		$sql = "SELECT topic_type_name FROM ".Config::Get('db.table.topic_type')." WHERE topic_type_id=?d" ;
+		if($aRows = $this->oDb->select($sql,$oTopicId)) {
+			$result = $aRows[0]['topic_type_name'];
+		}
+		return $result;
+	}
 	public function AddTopic(ModuleTopic_EntityTopic $oTopic) {
 		$sql = "INSERT INTO ".Config::Get('db.table.topic')." 
 			(blog_id,
@@ -33,9 +49,9 @@
 			topic_forbid_comment,			
 			topic_text_hash			
 			)
-			VALUES(?d,  ?d,	?,	?,	?,  ?, ?, ?d, ?d, ?d, ?, ?, ?)
+			VALUES(?d,  ?d,	?d,	?,	?,  ?, ?, ?d, ?d, ?d, ?, ?, ?)
 		";			
-		if ($iId=$this->oDb->query($sql,$oTopic->getBlogId(),$oTopic->getUserId(),$oTopic->getType(),$oTopic->getTitle(),
+		if ($iId=$this->oDb->query($sql,$oTopic->getBlogId(),$oTopic->getUserId(),$this->TopicTypeName2Id($oTopic->getType()),$oTopic->getTitle(),
 			$oTopic->getTags(),$oTopic->getDateAdd(),$oTopic->getUserIp(),$oTopic->getPublish(),$oTopic->getPublishDraft(),$oTopic->getPublishIndex(),$oTopic->getCutText(),$oTopic->getForbidComment(),$oTopic->getTextHash())) 
 		{
 			$oTopic->setId($iId);
Index: config/config.php
===================================================================
--- config/config.php	(revision 1053)
+++ config/config.php	(working copy)
@@ -235,6 +235,7 @@
 $config['db']['table']['user']                = '___db.table.prefix___user';
 $config['db']['table']['blog']                = '___db.table.prefix___blog';
 $config['db']['table']['topic']               = '___db.table.prefix___topic';
+$config['db']['table']['topic_type']          = '___db.table.prefix___topic_type';
 $config['db']['table']['topic_tag']           = '___db.table.prefix___topic_tag';
 $config['db']['table']['comment']             = '___db.table.prefix___comment';
 $config['db']['table']['vote']                = '___db.table.prefix___vote';
Index: install/upd.sql
===================================================================
--- install/upd.sql	(revision 0)
+++ install/upd.sql	(revision 0)
@@ -0,0 +1,12 @@
+create table if not exists `prefix_topic_type` (
+    `topic_type_id` INTEGER not null auto_increment,
+    `topic_type_name` varchar(32),
+    PRIMARY KEY (`topic_type_id`)
+) engine=innoDB default charset=utf8 auto_increment=1;
+insert into `prefix_topic_type` (`topic_type_id`,`topic_type_name`) values(0,'topic');
+insert into `prefix_topic_type` (`topic_type_id`,`topic_type_name`) values(0,'link');
+insert into `prefix_topic_type` (`topic_type_id`,`topic_type_name`) values(0,'question');
+insert into prefix_topic_type(`topic_type_name`)
+select topic_type from prefix_topic where topic_type not in ('topic','link','question') group by topic_type
+alter table prefix_topic add column `topic_type_id` integer not null default 0 after `topic_type`
+update prefix_topic set topic_type_id=(select topic_type_id from snn_topic_type where topic_type_name = topic_type)
avatar
надо просто topic_type сделать varchar, что уже предлагалось мной и по всей видимости было забыто в туче других тасков
avatar
1. Легких путей мы не ищем :)
2. Всетаки экономия на поле integer по сравнению допустим с Varchar(20) — 80% (4 байта vs 20 байт) а при условии что кодировка utf-8 еще больше (если я правильно помню определение размера символов в типе varchar mysql то varchar(20)-utf8 занимаєт 40 байт)
даже если не так то всеравно 80%
avatar
1. это вредно
2. экономия на спичках. 1 чар латиницы весит один байт даже в utf-8. при индексе на поле и ограниченном количестве вариантов, длина особого значения не имеет.
Только зарегистрированные и авторизованные пользователи могут оставлять комментарии.