[pLog-svn] r2121 - plog/branches/plog-1.1-ben/class/dao

ork at devel.plogworld.net ork at devel.plogworld.net
Tue May 31 00:23:36 GMT 2005


Author: ork
Date: 2005-05-31 00:23:35 +0000 (Tue, 31 May 2005)
New Revision: 2121

Modified:
   plog/branches/plog-1.1-ben/class/dao/articles.class.php
Log:
we will drastically reduce articles.class.php :) 
started to use BlogArticles() to fetch the articles of a blog. again *this will contain bugs* so see this as a work in progress.
searching will currently not work at all!

if BlogArticles() is fully implemented in Articles(), there is almost no need for sql statements anymore, exept when you insert or update an article.


Modified: plog/branches/plog-1.1-ben/class/dao/articles.class.php
===================================================================
--- plog/branches/plog-1.1-ben/class/dao/articles.class.php	2005-05-31 00:20:39 UTC (rev 2120)
+++ plog/branches/plog-1.1-ben/class/dao/articles.class.php	2005-05-31 00:23:35 UTC (rev 2121)
@@ -59,7 +59,7 @@
                 // we send the query and then fetch the first array with the result
                 $result = $this->Execute( $query );
 
-                if ( $result->RecordCount() == 0)
+                if ( $result->RecordCount() == 0 )
                     return false;
 
                 $article = $this->_fillArticleInformation( $result->FetchRow( $result ) );
@@ -72,6 +72,48 @@
         }
 
         /**
+         * Get all articles of a blog from the database and store it in the cache.
+         * 
+         * @param blogId Identifier of the blog which articles we want to fetch
+         * @return true
+         */
+        function getArticles( $blogId )
+        {
+            require_once( PLOG_CLASS_PATH . 'class/dao/blogarticles.class.php' );
+
+            $blogArticles = $this->_cache->getData( $blogId, CACHE_BLOGARTICLES );
+
+            if( !$blogArticles ) {
+                require_once( PLOG_CLASS_PATH . 'class/database/db.class.php' );
+
+                $prefix = $this->getPrefix();
+
+                // as much as i would like to, i don't know how to use a less complicated
+                // sql statement or how to use an abstract method to build an statement
+                // like this one.
+                $query = "SELECT a.id as id, c.category_id as category_id, a.date as date, 
+                                 a.status as status
+                          FROM {$prefix}article_categories_link c LEFT JOIN {$prefix}articles a 
+                               ON a.id = c.article_id
+                          WHERE a.blog_id = $blogId
+                          ORDER BY a.date DESC";
+
+                $result = $this->Execute( $query );
+
+                $rows = array();
+                while( $row = $result->FetchRow($result) ) {
+                    $rows[] = $row;
+                }
+
+                $blogArticles = new BlogArticles( $blogId, $rows );
+
+                $this->_cache->setData( $blogId, CACHE_BLOGARTICLES, $blogArticles );
+            }
+
+            return $blogArticles;
+        }
+
+        /**
          * Gets an article from the database, given its id
          *
          * @param artId Identifier of the article we want to fetch
@@ -272,13 +314,24 @@
 
 			// we need to keep the timestamp in mind
 			$date = $article->getDateObject();
-			$articleCorrectedDate = Timestamp::getDateWithOffset( $article->getDate(), -($article->getTimeOffset()));
-			$blogId = $article->getBlog();			
+			$articleCorrectedDate = Timestamp::getDateWithOffset( $article->getDate(), 
+                                                                 -($article->getTimeOffset()));
+			$blogId = $article->getBlog();
+
+            $whereConditions = array();
+            // '=' is the default when calculating the where conditions, but to
+            // have this look uniform, lets add the '=' anyway. :)
+            $whereConditions['blog_id'] = '=' . $article->getBlogId();
+            $whereConditions['date']    = '<' . $articleCorrectedDate;
+            $whereConditions['status']  = '=' . POST_STATUS_PUBLISHED;
 		
             // gets the article that is just previous in time
-            $query = "SELECT * FROM ".$this->getPrefix()."articles 
-			                   WHERE date < '".$articleCorrectedDate."' AND status = ".POST_STATUS_PUBLISHED." 
-									 AND blog_id = '".Db::qstr($blogId)."' ORDER BY date DESC LIMIT 1;";
+            $query = Db::buildSelectQuery( ARTICLES_TABLENAME,
+                                           array(),
+                                           $whereConditions,
+                                           null,
+                                           'date',
+                                           1 );
 									 
 			return( $this->_getBlogArticleFromQuery( $query, false ));
 		}
@@ -307,88 +360,27 @@
 		}
 		
 		/**
-		 * builds a WHERE clause for a query
-		 *
-		 * @private
-		 */
-		function buildWhere( $blogid, $date = -1, $amount = -1, $categoryId = 0, $status = 0, $userId = 0, $maxDate = 0, $searchTerms = "", $page = -1, $itemsPerPage = 15 )
-		{
-            include_once( PLOG_CLASS_PATH."class/database/db.class.php" );
-            $postStatus = $status;
-		    $prefix = $this->getPrefix();
-		    $query = "a.blog_id = ".Db::qstr($blogid);
-            if( $date != -1 )
-                $query .= " AND a.date+0 LIKE '$date%'";
-
-            // the common part "c.id = a.category_id" is needed so that
-            // we don't get one article row as many times as the amount of categories
-            // we have... due to the sql 'join' operation we're carrying out
-            if( $categoryId == -1 )
-                $query .= " AND c.id = l.category_id AND a.id = l.article_id ";
-            else {
-                if( $categoryId > 0 )
-                    $query .= " AND a.id = l.article_id AND l.category_id = $categoryId AND c.id = l.category_id";
-                else {
-                    $query .= " AND c.id = l.category_id AND a.id = l.article_id AND c.in_main_page = 1";
-                }
-            }
-
-            if( $status > 0 )
-                $query .= " AND a.status = '$postStatus'";
-            if( $userId > 0 )
-                $query .= " AND a.user_id = ".Db::qstr($userId);
-            if( $maxDate > 0 )
-                $query .= " AND a.date <= '$maxDate'";
-				
-			// in case there were some search terms specified as parameters...
-			if( $searchTerms != "" ) {
-				// load the class dynamically so that we don't have to waste memory
-				// if we're not going to need it!
-				include_once( PLOG_CLASS_PATH."class/dao/searchengine.class.php" );			
-				$searchEngine = new SearchEngine();
-				
-				// prepare the query string
-				$searchTerms = $searchEngine->_adaptSearchString( $searchTerms );
-				$whereString = $searchEngine->_generateSearchArticlesWhereString( $searchTerms );
-				
-				// and add it to the current search
-				$query .=" AND {$whereString} ";	
-			}
-				
-            if( $categoryId <= 0 )
-                $query .= " GROUP BY a.id ";
-
-                
-            return $query;
-		}
-		
-		/**
 		 * @see getBlogArticles
 		 */
-		function getNumBlogArticles( $blogid, $date = -1, $amount = -1, $categoryId = 0, $status = 0, $userId = 0, $maxDate = 0, $searchTerms = "" )
+		function getNumBlogArticles( $blogId,
+                                     $date = -1,
+                                     $amount = -1,
+                                     $categoryId = 0,
+                                     $status = POST_STATUS_PUBLISHED,
+                                     $userId = 0,
+                                     $maxDate = 0,
+                                     $searchTerms = "" )
 		{		
-            $postStatus = $status;
-		    $prefix = $this->getPrefix();			
-			$where = $this->buildWhere( $blogid, $date, $amount, $categoryId, $status, $userId, $maxDate, $searchTerms, $page, $itemsPerPage );	
-			$query = "SELECT COUNT(*) AS total FROM {$prefix}articles a, {$prefix}articles_categories c, 
-                             {$prefix}article_categories_link l";
-			if( $searchTerms != "" )
-				$query .= ", {$prefix}articles_text t ";
-				
-			if( $searchTerms != "" )
-				$query .= "WHERE t.article_id = a.id AND $where";
-			else
-				$query .= " WHERE $where";			
-				
-			if( $categoryId != -1 )
-				$query .= " GROUP BY a.id";
-                                                                      
-            $result = $this->Execute( $query );
-            
-            if( !$result )
-            	return 0;
-            	            	
-            return $result->RowCount();
+            $articles = $this->getBlogArticles( $blogId, 
+                                                $date, 
+                                                $amount, 
+                                                $categoryId, 
+                                                $status, 
+                                                $userId, 
+                                                $maxDate, 
+                                                $searchTerms );
+
+            return count($articles);
 		}
 
         /**
@@ -408,7 +400,7 @@
          * @return Returns an array with all the articles from the given blog
          */
 
-        function getBlogArticles( $blogid, 
+        function getBlogArticles( $blogId, 
                                   $date = -1, 
                                   $amount = -1, 
                                   $categoryId = 0, 
@@ -418,138 +410,41 @@
                                   $searchTerms = "", 
                                   $page = -1 )
         {
-            include_once( PLOG_CLASS_PATH.'class/dao/articlecategories.class.php' );
-            include_once( PLOG_CLASS_PATH.'class/database/db.class.php' );
+            $blogArticles      = $this->getArticles( $blogId );
+            $requestedArticles = $blogArticles->getArticleIdsByStatus( $status );
 
+            if( $categoryId > 0 ) {
+                $requestedArticles = $blogArticles->getArticleIdsByCategory( $categoryId, $requestedArticles );
+            }
 
-
-
-            $this->log->info("getBlogArticles $blogid, $date, $amount, $categoryId, $status, $userId, $maxDate, $searchTerms, $page");
-
-            $whereConditions = array();
-
-            $whereConditions['blog_id'] = $blogid;
-
-            // check the parameters to adjust the whereConditions accordingly
             if( $date != -1 ) {
+                $requestedArticles = $blogArticles->getArticleIdsByDate( $date, $requestedArticles );
             }
 
-            if( $categoryId != 0 ) {
-            }
 
-            if( $status != POST_STATUS_PUBLISHED ) {
-                $whereConditions['status'] = $status;
-            }
-
-            if( $userId != 0 ) {
-            }
-
             if( $maxDate != 0 ) {
+                $requestedArticles = $blogArticles->getArticleIdsBefore( $maxDate, $requestedArticles );
             }
 
             if( $searchTerms != '' ) {
+                // :TODO: implement this :-)
+                $requestedArticles = $this->searchArticles( $searchTerms, $requestedArticles );
             }
 
-            if( $page != -1 ) {
+            if( ($amount > 0) && ($date == -1) && ($page == -1 ) ) {
+                $requestedArticles = array_slice( $requestedArticles, 0, $amount );
             }
 
-            $query = Db::buildSelectQuery( ARTICLES_TABLENAME,
-                                           array('id'),
-                                           $whereConditions );
-
-            $this->log->info('new query: ' . $query );
-
-            // build the query
-            // the query gets quite complicated to build because we have to take care of plenty
-            // of conditions, such as the maximum date, the amount, the category,
-            // wether the category has to be shown in the main page or not, etc...
-            $postStatus = $status;
-            $prefix = $this->getPrefix();
-		    $where = $this->buildWhere( $blogid, $date, $amount, $categoryId, $status, $userId, $maxDate, $searchTerms, $page );
-            $query = "SELECT a.id as id, a.id, a.date,
-                             a.user_id,a.blog_id,a.status,a.properties,
-                             a.num_reads, a.slug, 1 AS relevance FROM {$prefix}articles a, {$prefix}articles_categories c, 
-                             {$prefix}article_categories_link l";
-			if( $searchTerms != "" )
-				$query .= ", {$prefix}articles_text t ";
-			$query .= " WHERE ";
-			if( $searchTerms != "" )
-				$query .= " t.article_id = a.id AND ";
-			$query .= " $where";
-                      
-	
-			// if we're doing a search, we should sort by relevance
-			if( $searchTerms != "" ) {
-				$query .= " ORDER BY relevance";			
-			}
-			else {
-				$query .= " ORDER BY a.date DESC";				
-			}
-			
-            // we don't need limits if we're getting the posts for a given day
-            if( ($amount > 0) && ($date == -1) && ($page == -1 ))
-                $query .= " LIMIT $amount;"; 
-            
-            // in case we're using a paged display
             if( $page > 0 ) {
-				$start = (($page - 1) * $amount);		        
-				$query .= " LIMIT $start, $amount";   
+				$start = (($page - 1) * $amount);
+                $requestedArticles = array_slice( $requestedArticles, $start, $amount );
             }
 
-            $this->log->info('old query: ' . $query );
-				
-			// execute the query
-            $result = $this->Execute( $query );
-
-            if( !$result )
-                return Array();
-				
-			if( $result->RowCount() == 0 )
-				return Array();
-            
-			$ids='';
-
-            while( $row = $result->FetchRow()) {
-            	$ids.='"'.$row["id"].'",';
-                $article = $this->_fillArticleHeaderInformation( $row );
-		        $articles[] =$article;
+            $articles = array();
+            foreach( $requestedArticles as $article ) {
+                $articles[] = $this->getArticle( $article );
             }
-
-            $ids = substr($ids, 0, -1);          
-            // $articleComments = $this->comments->getPostCommentsByIds( $ids, COMMENT_ORDER_NEWEST_FIRST, COMMENT_STATUS_ALL );
-			//$articleTrackbacks = $this->trackbacks->getArticleTrackbacksByIds( $ids );
-            if( $this->categories == null )
-                $this->categories = new ArticleCategories();
-			$articleCategories = $this->categories->getArticleCategoriesByIds( $ids, $blogid );
-			$articleTexts = $this->getArticlesText( $ids );
-            //$fields = $this->customfields->getArticleCustomFieldsValuesByIds( $ids );
-            
-            foreach( $articles as $article ) {
-            	$lastArticleId=$article->getId();
-            	// These are functions normally called by _fillArticleInformation
-				// But now I moved to test getPostCommentsByIds
-				$categoryIds = Array();
-				
-				// fill in the article texts
-				$article->setText( $articleTexts[$lastArticleId]['text'] );
-				$article->setTopic( $articleTexts[$lastArticleId]['topic'] );
-				
-				foreach( $articleCategories[$lastArticleId] as $category )
-					$categoryIds[] = $category->getId();
-					
-				$article->setCategoryIds( $categoryIds );
-				$article->setCategories( $articleCategories[$lastArticleId] );
-				//$article->setNumTrackbacks(sizeof($articleTrackbacks[$lastArticleId]));
-				//$article->setTrackbacks($articleTrackbacks[$lastArticleId]);
-				//$article->setTotalComments(sizeof($articleComments[$lastArticleId]));
-				//$article->setComments($articleComments[$lastArticleId]);
-				//$article->setFields( $fields[$lastArticleId] );
-
-				$fullarticles[]=$article;
-				$this->_memoryCache[$lastArticleId] = $article;       
-            }
-            
-            return $fullarticles;
+            return $articles;
         }
 		
 		/**
@@ -794,6 +689,9 @@
             // and save the custom fields
             $this->addArticleCustomFields( $postId, $newArticle->getBlog(), $newArticle->getFields());
 
+            // and finally clear the cache :)
+            $this->_cache->removeData( $newArticle->getBlogId(), CACHE_BLOGARTICLES );
+
             return $postId;
         }
 		
@@ -1054,6 +952,9 @@
             if( $this->_db->Affected_Rows() == 0 )
                 return false;
 
+            $this->_cache->removeData( $blogId, CACHE_BLOGARTICLES );
+            $this->_cache->removeData( $artId, CACHE_ARTICLES );
+
             return true;
         }
 		




More information about the pLog-svn mailing list