PHP code example of cosmicpe / blockdata

1. Go to this page and download the library: Download cosmicpe/blockdata library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cosmicpe / blockdata example snippets


final class MyPlugin extends PluginBase{

	/** @var BlockDataWorldManager */
	private $manager;
	
	protected function onEnable() : void{
		$this->manager = BlockDataWorldManager::create($this);
	}
}

class BlockHistoryData extends BlockData{ // stores when block was placed and by whom.

	public static function nbtDeserialize(CompoundTag $nbt) : BlockData{
		return new BlockHistoryData($nbt->getString("placer"), $nbt->getLong("timestamp"));
	}
	
	/** @var string */
	private $placer;

	/** @var int */
	private $timestamp;
	
	public function __construct(string $placer, ?int $timestamp = null){
		$this->placer = $placer;
		$this->timestamp = $timestamp ?? time();
	}
	
	public function getPlacer() : string{
		return $this->placer;
	}
	
	public function getTimestamp() : int{
		return $this->timestamp;
	}
	
	public function nbtSerialize() : CompoundTag{
		return CompoundTag::create()
			->setString("placer", $this->placer)
			->setLong("timestamp", $this->timestamp);
	}
}

const BLOCK_HISTORY_DATA = "blockhistory";
BlockDataFactory::register(self::BLOCK_HISTORY_DATA, BlockHistoryData::class);

public function onBlockPlace(BlockPlaceEvent $event) : void{
	$block = $event->getBlock();
	$pos = $block->getPos();
	$data = new BlockHistoryData($event->getPlayer()->getName());
	$this->manager->getWorld($pos->getWorld())->setBlockDataAt($pos->x, $pos->y, $pos->z, $data);
}

public function onPlayerInteract(PlayerInteractEvent $event) : void{
	if($event->getAction() === PlayerInteractEvent::RIGHT_CLICK_BLOCK && $event->getItem()->getId() === ItemIds::STICK){
		$block = $event->getBlock();
		$pos = $block->getPos();
		
		$data = $this->manager->get($pos->getWorld())->getBlockDataAt($pos->x, $pos->y, $pos->z);
		if($data instanceof BlockHistoryData){
			$event->getPlayer()->sendMessage(TextFormat::LIGHT_PURPLE . "This block was placed by " . TextFormat::WHITE . $data->getPlacer() . TextFormat::LIGHT_PURPLE . " on " . TextFormat::WHITE . gmdate("d-m-Y H:i:s", $data->getTimestamp()));
		}
	}
}