検索
ホームページバックエンド開発PHPチュートリアルDrupal Goes Social:Drupalに「好む」モジュールを構築します

この記事では、ユーザーがjQuery ajaxを使用して「いいね」を「いいね」とすることを可能にするDrupalモジュールを構築する方法を示しています。

Drupal goes Social: Building a

主要な機能:

    jquery ajaxを介した非同期の好み
  • liksのデータベースストレージ(ユーザーごと、投稿ごと)。
  • count updatesのようなリアルタイム。
  • ステータスとは異なります
  • モジュールの作成:

drupalインストールの

ディレクトリ内に
    フォルダーを作成します。
  1. 内部likepostsites/all/modules/custom
  2. を作成します
  3. likepost likepost.info
  4. create
:(初期
<code>name = likepost
description = Allows users to like Drupal posts.
core = 7.x</code>
の実装は完全性のために以下に含まれていますが、コア機能は後で追加されます)
  1. likepost.module hook_help
  2. データベーススキーマを定義するには
を作成します:
/**
 * @file
 * Main module file.
 */

/**
 * Implements hook_help().
 */
function likepost_help($path, $arg) {
  if ($path == 'admin/help#likepost') {
    $output = '<h3 id="t-About">' . t('About') . '</h3>';
    $output .= '<p>' . t('This module allows users to like posts in Drupal.') . '</p>';
    return $output;
  }
}
  1. likepost.installモジュールをインストールします。
  2. テーブルが作成されます
<?php
/**
 * Implements hook_schema().
 */
function likepost_schema() {
  $schema['likepost_table_for_likes'] = array(
    'description' => t('Stores post likes.'),
    'fields' => array(
      'userid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => t('User ID'),
      ),
      'nodeid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => t('Node ID'),
      ),
    ),
    'primary key' => array('userid', 'nodeid'),
  );
  return $schema;
}

likepost_table_for_likes

ajaxハンドリング(post.moduleなど):

Drupal goes Social: Building a

次の関数を

に追加します

いいねボタンを表示する(post.moduleなど):likepost.module

/**
 * Implements hook_menu().
 */
function likepost_menu() {
  $items['likepost/like/%'] = array(
    'title' => 'Like',
    'page callback' => 'likepost_like',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  return $items;
}

function likepost_like($nodeid) {
  $nodeid = (int) $nodeid;
  global $user;

  $like = likepost_get_like($nodeid, $user->uid);

  if ($like) {
    db_delete('likepost_table_for_likes')
      ->condition('userid', $user->uid)
      ->condition('nodeid', $nodeid)
      ->execute();
    $like = 0;
  } else {
    db_insert('likepost_table_for_likes')
      ->fields(array(
        'userid' => $user->uid,
        'nodeid' => $nodeid,
      ))
      ->execute();
    $like = 1;
  }

  $total_count = likepost_get_total_like($nodeid);
  drupal_json_output(array(
    'like_status' => $like,
    'total_count' => $total_count,
  ));
}

function likepost_get_total_like($nid) {
  $total_count = db_query('SELECT COUNT(*) FROM {likepost_table_for_likes} WHERE nodeid = :nodeid', array(':nodeid' => $nid))->fetchField();
  return (int) $total_count;
}

function likepost_get_like($nodeid, $userid) {
  $like = db_query('SELECT COUNT(*) FROM {likepost_table_for_likes} WHERE nodeid = :nodeid AND userid = :userid', array(':nodeid' => $nodeid, ':userid' => $userid))->fetchField();
  return (int) $like;
}

スタイリング(post.cssのような):

/**
 * Implements hook_node_view().
 */
function likepost_node_view($node, $view_mode) {
  if ($view_mode == 'full') {
    $node->content['likepost_display'] = array(
      '#markup' => display_like_post_details($node->nid),
      '#weight' => 100,
    );
    $node->content['#attached']['js'][] = array(
      'data' => drupal_get_path('module', 'likepost') . '/likepost.js',
    );
    $node->content['#attached']['css'][] = array(
      'data' => drupal_get_path('module', 'likepost') . '/likepost.css',
    );
  }
}

function display_like_post_details($nid) {
  global $user;
  $totalLike = likepost_get_total_like($nid);
  $hasCurrentUserLiked = likepost_get_like($nid, $user->uid);
  return theme('like_post', array(
    'nid' => $nid,
    'totalLike' => $totalLike,
    'hasCurrentUserLiked' => $hasCurrentUserLiked,
  ));
}

/**
 * Implements hook_theme().
 */
function likepost_theme() {
  $themes = array(
    'like_post' => array(
      'arguments' => array('nid', 'totalLike', 'hasCurrentUserLiked'),
    ),
  );
  return $themes;
}

function theme_like_post($arguments) {
  $nid = $arguments['nid'];
  $totalLike = $arguments['totalLike'];
  $hasCurrentUserLiked = $arguments['hasCurrentUserLiked'];
  global $base_url;
  $output = '<div>';
  $output .= 'Total number of likes on the post are ';
  $output .= '<div class="total_count">' . $totalLike . '</div>';
  $linkText = ($hasCurrentUserLiked == 0) ? 'Like' : 'Unlike';
  $output .= l($linkText, $base_url . '/likepost/like/' . $nid, array('attributes' => array('class' => 'like-link')));
  $output .= '</div>';
  return $output;
}

jQuery(likepost.js):

.likepost {
  border-style: dotted;
  border-color: #98bf21;
  padding: 10px;
}

.total_count {
  font-weight: bold;
}

.like-link {
  color: red;
}

.like-link:hover {
  color: red;
}

変更を行った後、Drupalのキャッシュをクリアすることを忘れないでください。 この詳細な説明により、好みのモジュールのより堅牢で理解できる実装が可能になるはずです。 スクリーンショットはプレースホルダーです。 Drupalサイトに実際のモジュール出力が表示されます。

以上がDrupal Goes Social:Drupalに「好む」モジュールを構築しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
unset()とsession_destroy()の違いは何ですか?unset()とsession_destroy()の違いは何ですか?May 04, 2025 am 12:19 AM

thedifferencebetferencefued fieneunset()andsession_destroy()isthatunset()clearsspecificsessionvariablesはsessionactiveであり、ssession_destroy()ターミナテンテンセッション

負荷分散のコンテキストでの粘着性セッション(セッションアフィニティ)とは何ですか?負荷分散のコンテキストでの粘着性セッション(セッションアフィニティ)とは何ですか?May 04, 2025 am 12:16 AM

StickysionsionsureuserRequestsoredtotheSameserverforsessiondataconsistency.1)Sessionidedificationisionidificationsisignivisionsignsignsuserstoserversusing okiesorurlmodifications.2)CondingRoutingDirectSSubSubSubsEntRequestStotheSameserver.3)LoadBalancingDistributeNewuser

PHPで利用可能なさまざまなセッション保存ハンドラーは何ですか?PHPで利用可能なさまざまなセッション保存ハンドラーは何ですか?May 04, 2025 am 12:14 AM

phpoffersvarioussionsionsavehandlers:1)ファイル:デフォルト、simplebutmaybottleneckonhigh-trafficsites.2)memcached:high-performance、yealforspeed-criticalapplications.3)redis:similartomcached、witordededpersistence.4)データベースの提供

PHPでのセッションとは何ですか?なぜそれらが使用されているのですか?PHPでのセッションとは何ですか?なぜそれらが使用されているのですか?May 04, 2025 am 12:12 AM

PHPでのセッションは、サーバー側のユーザーデータを保存して、複数のリクエスト間で状態を維持するメカニズムです。具体的には、1)セッションはsession_start()関数によって開始され、データは保存され、$ _Sessionスーパーグローバルアレイを読みます。 2)セッションデータはデフォルトでサーバーの一時ファイルに保存されますが、データベースまたはメモリストレージを介して最適化できます。 3)セッションを使用して、ユーザーのログインステータス追跡とショッピングカート管理機能を実現できます。 4)セッションの安全な送信とパフォーマンスの最適化に注意を払い、アプリケーションのセキュリティと効率を確保します。

PHPセッションのライフサイクルを説明してください。PHPセッションのライフサイクルを説明してください。May 04, 2025 am 12:04 AM

phpssionsStartWithsession_start()、figenateAuniqueidandcreateSaServerfile; theySistacrossRequestsandcanbemanbemanBeithsession_destroy()

絶対的なセッションタイムアウトとアイドルセッションのタイムアウトの違いは何ですか?絶対的なセッションタイムアウトとアイドルセッションのタイムアウトの違いは何ですか?May 03, 2025 am 12:21 AM

絶対セッションのタイムアウトはセッションの作成時に開始され、アイドルセッションタイムアウトはユーザーの操作なしに開始されます。絶対セッションタイムアウトは、金融アプリケーションなど、セッションライフサイクルの厳格な制御が必要なシナリオに適しています。アイドルセッションタイムアウトは、ソーシャルメディアなど、ユーザーが長い間セッションをアクティブに保つことを望んでいるアプリケーションに適しています。

セッションがサーバーで機能していない場合、どのような措置を講じますか?セッションがサーバーで機能していない場合、どのような措置を講じますか?May 03, 2025 am 12:19 AM

サーバーセッションの障害は、手順に従って解決できます。1。セッションが正しく設定されていることを確認するために、サーバーの構成を確認します。 2.クライアントCookieを確認し、ブラウザがそれをサポートしていることを確認し、正しく送信します。 3. Redisなどのセッションストレージサービスを確認して、それらが正常に動作していることを確認します。 4.アプリケーションコードを確認して、正しいセッションロジックを確認します。これらの手順を通じて、会話の問題を効果的に診断および修復し、ユーザーエクスペリエンスを改善することができます。

session_start()関数の重要性は何ですか?session_start()関数の重要性は何ですか?May 03, 2025 am 12:18 AM

session_start()iscrucialinphpformangingusersions.1)itInitiateSanewsessionifnoneExists、2)resumesanexistingsession、および3)SetSessionCookieforcontinuityAcrossRequests、ApplicationslicationSliviseSlikeUserauthicationAnticatent。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。